Show/hide Div With Id Based On Data Attribute (onclick)
I have the following List:
- Main
Solution 1:
You can use on click event on a elements inside ul li and get the attribute
data-related
. Then you can use this and find div with id same asdata-related
and toggle(hide/show or anything else):$("ul li a").on("click", function() { $("div[id=" + $(this).attr("data-related") + "]").toggle(); });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><li><ahref="#"class="active"data-related="main">Main</a></li><li><ahref="#"data-related="title_1">Title 1</a></li><li><ahref="#"data-related="title_2">Title 2</a></li><li><ahref="#"data-related="title_3">Title 3</a></li><li><ahref="#"data-related="title_4">Title 4</a></li></ul><divid="main">... Content ...</div><divid="title_1">... Content ...</div><divid="title_2">... Content ...</div><divid="title_3">... Content ...</div><divid="title_4">... Content ...</div>
Another example with addClass/removeClass:
$("ul li a").on("click", function() { $("div").removeClass("activeLnk"); $("div[id=" + $(this).attr("data-related") + "]").addClass("activeLnk"); });
.activeLnk { background: red; }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><li><ahref="#"class="active"data-related="main">Main</a></li><li><ahref="#"data-related="title_1">Title 1</a></li><li><ahref="#"data-related="title_2">Title 2</a></li><li><ahref="#"data-related="title_3">Title 3</a></li><li><ahref="#"data-related="title_4">Title 4</a></li></ul><divid="main">... Content ...</div><divid="title_1">... Content ...</div><divid="title_2">... Content ...</div><divid="title_3">... Content ...</div><divid="title_4">... Content ...</div>
Solution 2:
you could match the ID with the data-attr like this:
$("div").each(function(){ $(this).hide(); if($(this).attr('id') == 'main') { $(this).show(); } }); $('a').on( "click", function(e) { e.preventDefault(); var id = $(this).attr('data-related'); $("div").each(function(){ $(this).hide(); if($(this).attr('id') == id) { $(this).show(); } }); });
Solution 3:
Add a class to this html code :
<div id="main" class="tab">... Content ...</div> <div id="title_1" class="tab">... Content ...</div> <div id="title_2" class="tab">... Content ...</div> <div id="title_3" class="tab">... Content ...</div> <div id="title_4" class="tab">... Content ...</div>
Put this in a script tag :
$('ul a').click(function(e){ $('ul li').removeClass('actif'); $(this).find('li').addClass('actif'); $('.tab').hide(); $('#'+$(this).attr('data-related')).show(); //This is also valid//$('#'+$(this).data('related')).show(); e.preventDefault(); });
Post a Comment for "Show/hide Div With Id Based On Data Attribute (onclick)"