Jack Vawdrey Jack Vawdrey - 1 month ago 9
CSS Question

jQuery change z-index with data-*

I have divs that all occupy the same space, and I want to set up jQuery that has one div come on top of the other as different tabs are clicked. I assume this has to be done by changing the z-index attribute using a data-* attribute that connects the tab to the div.

/*The tabs to be clicked*/

<ul class="tabs">
<li class="tab" data-tabcontainer-id="websites" style="background-color:#1aa3ff;">Websites</li>
<li class="tab" data-tabcontainer-id="sitemaps">Sitemaps</li>
<li class="tab" data-tabcontainer-id="pages">Pages</li>
</ul>

/*The divs that need to come on top of each other*/

<div id="websites" class="tabcontainer">Websites</div>
<div id="sitemaps" class="tabcontainer">Sitemaps</div>
<div id="pages" class="tabcontainer">Pages</div>

Answer

DEMO

http://plnkr.co/edit/aNomjINfbYYrRUhMj63A?p=preview

This is how you can change the z-index property using the data attribute.

JS:

jQuery(document).ready(function(){
  $('.tab').click(function(){
    var target = $(this).data('tabcontainer-id');
    $('.tabcontainer').css('z-index', '0'); //resets z-index to 0 for all other
    $('.tabcontainer#'+target).css('z-index', '1'); //sets z-index for current target to 1
  })  
});

I wrote the answer just to meet what you were asking. But reading your question I think you should have a look at the tabs feature by jQuery UI. May be it will help.

https://jqueryui.com/tabs/