1

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.

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
syedfa
  • 2,801
  • 1
  • 41
  • 74
  • 3
    Instead of setting the style by `id`, set it by `class`, and add/remove the class when you want the highlighting to be on/off. – Ian May 02 '13 at 15:45

4 Answers4

0

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 class with JavaScript

Community
  • 1
  • 1
Salvatorelab
  • 11,614
  • 6
  • 53
  • 80
0

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.

DaGLiMiOuX
  • 889
  • 9
  • 28
0
function toggleHighlight(on)
{
  var el = document.getElementById('highlight');

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

called as:

toggleHighlight(true);  // turn on
toggleHighlight(false); // turn off
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

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

// show the element
$('#highlight').hide();
// hide the element
$('#highlight').show();

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

a--m
  • 4,716
  • 1
  • 39
  • 59