user2058201
user2058201

Reputation: 23

Clicking certain link to show a certain image from a collection of images?

My JQuery experience is limited. Any help greatly appreciated.

I have an un-ordered list containing 5 list items. I have five images, i would like a different image to show depending upon which list item is clicked.

Example: How many apples have you eaten today? Select 1 2 3 4 or 5. Clicking number 5 would show the image of 5 apples.

Each image will display within the same replacing the previous image.

The selection needs to be "continuous" throughout the user experience. I.E the user needs to be able to select 1 2 3 4 5 as many times as they like.

I imagine chaining 5 If, Else statements is not very efficient?

Does this require a Loop function?

Many Thanks

Upvotes: 0

Views: 772

Answers (1)

kidwon
kidwon

Reputation: 4504

The most primitive is using index if you are positive that each list element coresponds in sequnce order to the desired image.

example: http://jsfiddle.net/w1xafnkg/

html:

<ul id="list">
    <li>1 apple</li>
    <li>2 apple</li>
    <li>3 apple</li>
    <li>4 apple</li>
    <li>5 apple</li>
</ul>

<div id="images">
    <img />
    <img />
    <img />
    <img />
    <img />
</div>

script:

var lastShown;
$('#list').on('click', 'li', function() {
    var index = $(this).index();

    if (lastShown)
        lastShown.hide();

    lastShown = $('#images img:eq(' + index + ')')
    lastShown.show();
});

About your second question:

example: http://jsfiddle.net/w1xafnkg/1/

script

    function initListToImageBind(defaultIndex) {
        var lastShown;
        if (!isNaN(defaultIndex)) {
            lastShown = $('#images img:eq(' + defaultIndex + ')').show();
        }

        $('#list').on('click', 'li', function () {
            var index = $(this).index();
            if (lastShown) lastShown.hide();
            lastShown = $('#images img:eq(' + index + ')')
            lastShown.show();
        });
    }

    /* invoking the function defined with the desired index number of image to 
be shown by default */
    initListToImageBind(4);

Bear in mind that the indexing starts from 0, so let's say you want the third image shown by default then the index is going to be 2 !!!

Upvotes: 1

Related Questions