Rotan075 Rotan075 - 1 year ago 72
HTML Question

Set display of div by using the data-target attribute

Hello I got a question regarding setting the display of a div with the use of the

attribute. I have the following HTML code:

<div class="page page-current" id="home">
<a href="#" class="next" data-target="#about">Go to about</a>

<div class="page page-section" id="about">
<a href="#" class="next" data-target="#portfolio">Go to portfolio</a>

<div class="page page-section" id="portfolio">

As can seen above, the div's that contain the class:
are initial hidden by CSS using:
. Now I managed to create a generic JS code that checks which div should be made visible:

var target = $(this).data("target");

The problem with this is that it adds to the second div the class:
but the first div also still contains this class.

Can anyone guide me in the right direction how I could solve this is in a generic way so that only one div at the time can contain the class:

I have created a JSFIDDLE of this problem.

Answer Source

To do what you require you need to remove the page-current from the current page, and add it to the new element, while removing page-section from the new element and adding it back on to the old.

You can do this by using the toggleClass() method, like this:

$(".next").click(function() {
    var target = $(this).data("target");
    $('.page-current').add(target).toggleClass('page-current page-section');

Working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download