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>

its corresponding CSS code looks like this:

#container {
#highlight {
    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.


function toggleHighlight(on)
  var el = document.getElementById('highlight');

  el.style['display'] = on ? 'block' : 'none';

called as:

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

You can create a CSS class rule:

.hide {
    display: none;
    visibility: hidden;

And with javascript add or remove that class to the elements you want to toggle. This way when an element has class="none" it won't be shown, and just by removing class="none" it will show up again.

Here there is a good question about adding and removing classes with pure javascript: Change an element's CSS class with JavaScript

If I understand what you said, you want that when someone goes with pointer through a div, show or hide it. If I'm not wrong, you only have to use #highlight:hover {...} and no javascript is needed. Also, you have to add display: block property and by default it has to be display: none.

In your Fiddle I can see you use jquery, so this can be achieved using this code:

// show the element
// hide the element

I've updated your example to test the hide function.

Need Your Help

How to set and change the culture in WPF

.net wpf localization

I have a .NET 4.0 WPF application where the user can change the language (culture)

C++ datastructure (standard library) dump (like the python print function)

c++ data-structures recursion recursive-datastructures

When I'm programming in python it's very convenient to just print whatever datastructure you want to inspect on the screen. Does there exist something like this in C++ for STL datastructures?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.