Hover Effect in Javascript (like in FireBug)
Or: Making a Select element effect.
I’ve been trying to create an element selection tool for Javascript.
The effect would be similar to FireBug (for those who know) -
I just wanted to highlight whichever element the user has his mouse on.
This proved to be more difficult than I thought.
I started with this short script:
1
2
3
4
5
6
highlight_elements.hover(function(e) {
$(this).addClass('is_hovered');
});
}, function(e) {
$(this).removeClass('is_hovered');
});
(working example)
This seem to fail when going into child elements, where the parent element didn’t trigger
the “unhover” event (and thus stayed highlighted).
After a bit of tinkering, I wrote the following solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$('body *:visible').hover(function(e) {
$(this).addClass('is_hovered');
elem = $(this);
//going over the highlighted items
$('body *:visible').filter('.is_hovered').each(function(k,v) {
if (elem.get(0) != v) {
/* highlighted item is NOT the current item being hovered
This means - it's a parent element, let's mark it (for when we get out of the child element),
and unhighlight it */
$(v).attr('child_highlighted',1).removeClass('is_hovered');
}</p>
<p> });
}, function(e) {
$(this).removeClass('is_hovered');
//if the target element (the element now being hovered) is parent, highlight it and remove the marking
if ($(e.toElement).attr('child_highlighted')) {
$(e.toElement).addClass('is_hovered').removeAttr('child_highlighted');
}
$(this).removeClass('is_hovered');
});
(working example)
There's not much need for clarification, as most of it is written in the comments.
Of course, you could have an extra Highlight function
(to actually do something with the current selected element), and what-not.
I just wanted to show the (relatively) hard part.
I wish there was an easier way to do this (not that this is such a bad solution).
Until next time!