JavaScript: Toggle hide/show automatically

From The Travis van der Font Wiki
Jump to: navigation, search
const show = function (element)
{
   element.style.display = 'block';
};

const hide = function (element)
{
   element.style.display = 'none';
};

const toggleHideShow = function (element)
{
   // if the element is visible, hide it
   if (window.getComputedStyle(element).display === 'block')
   {
      hide(element);
   }
   else
   {
      show(element);
   }
};

jQuery

$('.class_name').click(function (event)
{
    toggleHideShow('#id_name'); // autodetect    
});

function toggleHideShow(id)
{
    if ($(id).is(':visible'))
    {
        $(id).hide();
    }
    else
    {
        $(id).show();
    }
}

Reference(s)