Adam Merrifield
Adam Merrifield

Reputation: 10407

Jquery Image Swap onLoad

I want to change the src of a set of images of a class to each image's title attribute. Is there any easier way to do this?

    <img src="" title="images/1.png" class="images" />
    <img src="" title="images/2.png" class="images" />
    <img src="" title="images/3.png" class="images" />
    <img src="" title="images/4.png" class="images" />
    <img src="" title="images/5.png" class="images" />
<script>
    $(function(){
    var newImage = $(this).attr('title')
    $('.images').attr(src, ''+ newImage +'');
    });
</script>

But this does not work correctly.

Upvotes: 1

Views: 979

Answers (2)

spinon
spinon

Reputation: 10847

Here is a simple working example: http://jsfiddle.net/SwcYK/

$(function()
{
    var $images = $("img.images");

    for (var i = 0; i < $images.length; i++)
    {
        $images[i].src = $images[i].title;
    }
});

Upvotes: 1

PriorityMark
PriorityMark

Reputation: 3247

It wouldn't, because you're getting the title from just the first image. Try something like this:

$(function() {
  $('img.images').each(function () {
    var $this = $(this);
    $this.attr('src', $this.attr('title'));
  }
});

Upvotes: 2

Related Questions