0

I want to update the src of an image depending on a link that I click with jquery. I have four links and an image displayed above.

If I click on the first link, I want the src of the image to change of the first element of the container array. It should increment like that until reaching the last element of the array.

What is the best way to do this basic approach?

<figure>
    <img src="http://lorempixel.com/g/400/200/" />
    <figcaption>
        <nav>
            <a href="#">Image One</a>
            <a href="#">Image Two</a>
            <a href="#">Image Three</a>
            <a href="#">Image Four</a>
        </nav>
    </figcaption>
</figure>

jquery:

$(function(){

    var container = [
       "http://lorempixel.com/g/400/200/",
       "http://lorempixel.com/g/400/200/",
       "http://lorempixel.com/g/400/200/",
       "http://lorempixel.com/g/400/200/"
    ];

    var i;
    $("nav a").on("click", function(){
            for(i = 0; i < 4; i++) {
                $("img").attr("src", container[i]);
            }
    });

});

1 Answer 1

1

Use this:

var container = [
    "http://lorempixel.com/g/400/200/",
    "http://lorempixel.com/g/400/200/",
    "http://lorempixel.com/g/400/200/",
    "http://lorempixel.com/g/400/200/"];

$("nav a").on("click", function () {
    $("img").prop("src", container[$(this).index()]);
});

jsFiddle example

You can use jQuery's .index() function to find which link was clicked on and select the corresponding array element. Both are zero-based.

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

3 Comments

Thank you! Do I have to use prop() or can I also use attr()?
That depends on the version of jQuery you're using. With the latest versions use prop().
@Tantra - Did something not work? I see you've unaccepted my answer.

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.