0

I have a list of images (thumbs) near a container with one image. I want jQuery to count the index of the <a> element, and then replace the number of the src attribute of the image below.

I mean, considering this code:

<ul class="thumbs">
    <li><a href="#"><img src="img1.jpg" alt="image here"/></a></li>
    <li><a href="#"><img src="img2.jpg" alt="image here"/></a></li>
    <li><a href="#"><img src="img3.jpg" alt="image here"/></a></li>
    <li><a href="#"><img src="img4.jpg" alt="image here"/></a></li>
</ul>

<div class="container">
    <img src="img1.jpg" alt="destiny image here"/>
</div>

The expected behavior is, when user clicks the second <a>, the .container img change its src attribute to img1.jpg. And when click the fourth <a> the attribute should change to img3.jpg.

I have got this far: jsFiddle demo

$(document).ready(function() {
    $(".thumbs li a").click(function () {
        //$('div.container').toggleClass('on');
        var index = $(".thumbs li a").index(this);
        $("div.container img[src^='img']").replaceWith("img" + index + ".jpg");
    });
});

It doesn't does absolutely nothing. I don't think to understand properly the .replaceWith method.

Also, the commented line works fine when it's alone... when the rest of code is present div.container don't change its class. Is this related to the way I declare the variable?

2

2 Answers 2

3

You aren't replacing the attribute, you are replacing the img element.

you need to set the attribute with .attr('src', value).

replaceWith() is for replacing elements with other html elements.

Sign up to request clarification or add additional context in comments.

1 Comment

That's, that's it what I was searching for! Thanks :)
3

Keep it simple, get rid of the index. Just get the src. Use this code:

$(document).ready(function() {
    $(".thumbs li a").click(function () {
        //Get the src of the clicked image
        var src = $(this).find('img').attr('src');

        //Set the src to the container image
        $("div.container img").attr('src', src);
    });
});

Demo: http://jsfiddle.net/Stijntjhe/HvTpv/5/

8 Comments

It's hard to see it working without working images. Use Chrome's console to inspect the element.
the code would also benefit from event delegation - use $('.thumbs').on('click', 'li a', ...)
this is the answer. more concise
not least because using .index() will require an off-by-one adjustment because it's zero-based.
I like your solution too, is even more elegant. I'll give the accepted answer to Brad because it match more with the question (for other users who wants to do something with the .index method), but thank you very much indeed ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.