Search code examples
javascripthtmlcsshighlighting

Turn an element's CSS on/off using JavaScript


I currently have the following block of HTML that I am using to highlight a particular area of a .png file:

<div id="container">
    <img src="http://www.placekitten.com/200/200" />
    <div id="highlight"></div>
</div>

its corresponding CSS code looks like this:

#container {
    positioon:relative;
}
#highlight {
    position:absolute;
    width:75px;
    height:75px;
    top:75px;
    left:75px;
    background: rgba(255, 0, 0, 0.4);
}

Both can be seen working together on the following page.

The code works fine, but what I would like to do is figure out a way to turn the highlighting on/off by having a JavaScript function in control of this feature. I am a JavaScript novice, and not sure how to approach this. All I want is to be able to pass a variable to a JavaScript function, and based on this boolean variable, either activate, or deactivate the shading.

Can anyone show me how to do this?

Thanks in advance to all who reply.


Solution

  • function toggleHighlight(on)
    {
      var el = document.getElementById('highlight');
    
      el.style['display'] = on ? 'block' : 'none';
    }
    

    called as:

    toggleHighlight(true);  // turn on
    toggleHighlight(false); // turn off