Next and Previous Navigation by showing corresponding DIV

html, javascript, navigation

Solution

Given the following HTML:

<div class="sample">div1</div>
<div class="sample">div2</div>
<div class="sample">div3</div>
<a href="#" id="display" class="display">next</a>
<a href="#" id="display1" class="display">prev</a>

The following jQuery seems to achieve your requirements:

// selects all the divs of class='sample',hides them, finds the first, and shows it
$('div.sample').hide().first().show();

// binds a click event-handler to a elements whose class='display'
$('a.display').on('click', function(e) {
    // prevents the default action of the link
    e.preventDefault();

    // assigns the currently visible div.sample element to a variable
    var that = $('div.sample:visible'),
        // assigns the text of the clicked-link to a variable for comparison purposes
        t = $(this).text();

    // checks if it was the 'next' link, and ensures there's a div to show after the currently-shown one
    if (t == 'next' && that.next('div.sample').length > 0) {
        // hides all the div.sample elements
        $('div.sample').hide();

        // shows the 'next'
        that.next('div.sample').show()
    }
    // exactly the same as above, but checking that it's the 'prev' link
    // and that there's a div 'before' the currently-shown element.
    else if (t == 'prev' && that.prev('div.sample').length > 0) {
        $('div.sample').hide();
        that.hide().prev('div.sample').show()
    }
});​

JS Fiddle demo.

References:

- `first()`.

- `hide()`.

- `next()`.

- `on()`.

- `prev()`.

- `show()`.

- `text()`.

- `:visible` selector.

Addenda:

A quick explanation of why I changed the html in the linked demo:

<div name="sample">div1</div>
<div name="sample">div2</div>
<div name="sample">div3</div>
<a href="#" id="display" value="display">next</div>
<a href="#" id="display1" value="display">prev</div>

The `name` attribute, in a `div` serves no purpose. Certainly not if all the elements are sharing the same name (they're not `input` elements, they're linked-to by an `a`, so use a `class` name).

The value attribute has no association with an `a` element, and serves, so far as I can tell, no purpose. For this, in the script above, I chose, again, to use a `class` name, since the same 'value' of the attribute was shared, though a `data-*` attribute could have been used, and would have been valid.

The closing `</div>` tags weren't closing anything, so they were changed to `</a>`.

Problem

I am in the lookout for a script that can show one DIV at a time and Hide the rest (2 in the example I took)additionally I want the user to navigate back and forth i.e Once the user clicks next DIV 1 is displayed so on till DIV3 He should also be able to traverse from DIV2 - DIV1 and so on I did find this development interesting http://jsfiddle.net/meetrk85/Y7mfF/ Thanks a billion in advance.....

Original source