Display and hide a block using jQuery

February 6th, 2014 by Alex Leave a reply »

There is a very simple way to bind the jQuery’s toggle() function for all elements, here’s how. Imagine you have this simple structure, and would like to show the block if it’s hidden or hide the block if it’s visible:

<a href="#" data-toggle="thatblock">Show me!</a>
 
<div id="thatblock" style="display: none">
  I will appear when you click on that button ;)
</div>

Well there’s a very simple way, and you don’t need to repeat it for every element

$(function() {
  $('*[data-toggle]').click(function() {
    $('#'+$(this).attr('data-toggle')).toggle();
    return false;
  });
});

Done! 😀

UPDATE

Second option is to trigger visibility using a CSS class (should be faster according to JSPerf):

.hidden { display: none }
<a href="#" data-toggle="thatblock">Show me!</a>
 
<div id="thatblock" class="hidden">
  I will appear when you click on that button ;)
</div>
$(function() {
  $('*[data-toggle]').click(function() {
    $('#'+$(this).attr('data-toggle')).toggleClass('hidden');
    return false;
  });
});

Comments are closed.