Show/Hide Elements with primitive JS

Posted by admin at December 30, 2016

We are going to look at how to toggle the appearance of HTML elements in the DOM using JavaScript. First of all, I know they are better solutions for implementing this (JQuery, being a perfect example), but we will be working with good ol’ plain JavaScript.

CSS:

First off, we define the class for hiding HTML elements.


.hide {display:none}

Hide It:

To hide the HTML Element, the function function merely adds the hidden class ‘hide’ to the className property.



function hide(ctrl)
{
    // append the hidden class 'null' to the element's class
    ctrl.className += ' hide';
}

Show It:

Also, to display, the function function removes the class defined above from the class property.


function show(ctrl)
{
    // replace the hidden class 'null' with '' in the  element's
    ctrl.className = ctrl.className.replace(/ hide/, '');
}

Single:

Below is a function that toggles the class of a single HTML element.



function show_hide(ctrl, lock)
{
    // append space: to ensure that the needle ' hide' works in the haystack
    var class_name = ' ' + ctrl.className;
    
    if (
        lock === undefined
        || lock == ''
    )
    {
        lock = '';
    
        // if the hidden class is found in the element's class
        if (class_name.search(' hide') > 0)
        {
            // show the element 
            show(ctrl);
        }
        else
        {
            // hide the element
            hide(ctrl);
        }
    }
    else
    {
        if (lock == 'show')
        {
            // show the element 
            show(ctrl);
        }
        else if (lock == 'hide')
        {
            // hide the element
            hide(ctrl);
        }
    }
    
}

HTML



<div name="div_id">Toggle this div display....</div>

<a href="#" onclick="show_hide(div_id);">toggle</a>
   
<a href="#" onclick="show_hide(div_id, 'show');">show</a>
   
<a href="#" onclick="show_hide(div_id, 'hide');">hide</a>

Multiple:

The function below uses the show_hide() function above to toggle all HTML elements that have the same name property


function multi_show_hide(ctrlname, lock)
{
    // get all the elements by the name
    var ctrls = document.getElementsByName(ctrlname);
    
    for (i=0; i<ctrls.length; i++)
    {
        // show or hide the element
        show_hide(ctrls[i], lock);
    }
    
}

HTML


<div name="all_divs">HTML Element 1</div>
<div name="all_divs">HTML Element 2</div>
<div name="all_divs">HTML Element 3</div>
<div name="all_divs">HTML Element 4</div>
<div name="all_divs">HTML Element 5</div>
<div name="all_divs">HTML Element 6</div>
<div name="all_divs">HTML Element 7</div>

<a href="#" onclick="show_hide(all_divs);">toggle</a>
   
<a href="#" onclick="show_hide(all_divs, 'show');">show</a>
   
<a href="#" onclick="show_hide(all_divs, 'hide');">hide</a>
   0 likes

Suggested Read