Set display div using target-data attribute

Hello, I have a question regarding setting the display of a div using an attribute data-target. I have the following HTML code:

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

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

<div class="page page-section" id="portfolio">
  PAGE 3
</div>

As seen above, div, containing class: page-sectionfirst hiding CSS, using: display:none. Now I managed to create a generic JS code that checks which div should be visible:

$(".next").click(function(){
    var target = $(this).data("target");
  $(target).addClass("page-current");  
})

The problem is that it adds the class: to the second div page-current, but the first div also contains this class.

Can someone lead me in the right direction, how can I solve this, is a general way, so that only one div at a time can contain a class: page-current

I created JSFIDDLE of this problem.

+4
1

, , page-current , page-section .

, toggleClass(), :

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

+6

Source: https://habr.com/ru/post/1649299/


All Articles