0

I am trying to change the src of an image when clicking on individual links (I only have 3).

So if I click on link #1, the src changes, if I click on link #2 it changes to something else, kind of like a basic image slider.

Here is a simplified example:http://jsfiddle.net/BVmUL/164/

the jquery I tried:

var images = [
    "http://lorempixel.com/400/200/",
    "http://linenwoods.com/images/kitten.png",
    "http://linenwoods.com/images/third.png"
],
    links = $("ol.list-inline > li > a"),
    img = $("figure > img");

links.each(function(){
    links.click(function(){
        img.prop("src", images[links.index()]);
        console.log($(this).index()); // only gives back 0 instead of 0,1,2 like
                                      // I expected ...
    });
});

How can I do something like this using jquery?

1 Answer 1

3

The anchors are inside LI elements and have no siblings, as such their index is always zero.

var images = [
    "http://lorempixel.com/400/200/",
    "http://linenwoods.com/images/kitten.png",
    "http://linenwoods.com/images/third.png"
],
    links = $("ol.list-inline > li > a"),
    img = $("figure > img");


    links.on('click', function(){
        img.prop("src", images[$(this).closest('li').index()]);
    });
});

get the index() of the parent LI instead

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

2 Comments

Ah, that makes sense .. thank you for the fast response! will accept in 9 minutes.
I forgot to ask: can I add fadeIn() or fadeOut() easily with your code to add a fade effect when the img changes?

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.