Steggie Steggie - 28 days ago 14
HTML Question

Echo ALT attribute of random image

I have this little script that displays a random image, which is:

<img src="<?php echo bloginfo('template_url');?>/img/members/00<?php $random = rand(1,7); echo $random; ?>.jpg"alt="[ Random Image ]">


This makes the image src
src="example.com/images/001.jpg" alt="[ Random Image ]">
the (1,7) in the script adds the number of the image
001.jpg
to
007.jpg
.

Now what I would like is to change the
"[ Random Image ]"
in to
"$my_alt"
and have it display (echo) the alt attribute of the image in a
<h2 class="myAlt">...</h2>
tag.

I'm not that of a coder, so I don't really know how to do this. I believe I would first need to give
my_alt
a value. So I would go by:

if {image src="example.com/images/001.jpg" $my_alt = "My first Alt"}
else if {image src="example.com/images/002.jpg" $my_alt = "My second Alt"}


and then where I want the value of the alt to be placed add the code:
<h2 class="myAlt"><?php echo $my_alt(); ?></h2>


Am I doing this correct, is this the right way to go? Like I said I'm not that good at coding, so thanks for the help.

Answer

I got your problem. Try this to see if it works:

<!-- I am gonna make a sample template so that you may understand how to use my solution for your specific issue -->
 <div class="imageContainer">
    <img src="something" alt="Image1" />
    <h2 class="myAlt"></h2>
</div>
<div class="imageContainer">
    <img src="something" alt="Image2" />
    <h2 class="myAlt"></h2>
</div>
<div class="imageContainer">
    <img src="something" alt="Image3" />
    <h2 class="myAlt"></h2>
</div>
<div class="imageContainer">
    <img src="something" alt="Image4" />
    <h2 class="myAlt"></h2>
</div>

<script>
$('.imageContainer').each(function(){
    $(this).find('.myAlt').html($(this).find('img').attr('alt'));
});
</script>

It will show the respective alt below every image.

for particular two images

// giving alt dynimically
    $('img').each(function(){
        if($(this).attr('src')==='image 001.jpg'){
            $(this).attr('alt','person x');
        }
        else if($(this).attr('src')==='image 002.jpg'){
            $(this).attr('alt','person y');
        }
    });

its just an idea, you need to modify it to suit your particular problem. Good luck. I hope it helps