Reputation: 3243
I am trying to add border only to the element where my mouse is, but my code is add border to its parent element as well,
My code:
jQuery('body').mousemove(function(e){
var el = e.target;
jQuery(el).hover(function(){
jQuery(this).css('outline','solid 2px #000');
},function(){
jQuery(this).css('outline','');
});
});
Fiddle here: http://jsfiddle.net/howtoplease/gk8t7/
Upvotes: 0
Views: 308
Reputation: 95028
The main problem is the use of .hover
. .hover
uses the events mouseenter
and mouseleave
. mouseleave
won't trigger on a parent element when you enter the child element, therefore the outline will stay till you "leave" the parent and all children. Additionally, you need to prevent a mouseover
on the child from propagating to a parent.
//jQuery('body').mousemove(function(e){
//var el = e.target;
jQuery('div').mouseover(function (e) {
e.stopPropagation();
jQuery(this).css('outline', 'solid 2px #000');
}).mouseout(function () {
jQuery(this).css('outline', '');
});
//});
also, i don't quite understand why you are using the body
mousemove
, is this a debugging tool where you won't know which elements you want it defined on?
Upvotes: 5
Reputation: 106
You can do this very simply. Add a class name to all elements (in this case I am just using 'div' since there are only divs) that should get the outline and add the following event listener to your js.
jQuery('div').mousemove(function (e) {
$el = $(e.target)
$('div').removeClass('outline')
$el.addClass('outline')
});
Upvotes: 2
Reputation: 6926
Use the parents() method of jQuery if you don't want to use classes.
$('div').hover(function(e){
$(this).parents().css('outline','');
jQuery(this).css('outline','solid 2px #000');
},function(){
$(this).parent('div').css('outline','solid 2px #000');
jQuery(this).css('outline','');
});
If you mouse out, you are already on the parent element actually and you never moused out of it, so you find the parent div wrapping the $(this)
using parent() and giving it border to simulate.
Example: http://jsfiddle.net/gk8t7/13/
Upvotes: 2
Reputation: 146310
Use a class to change the outline, otherwise you never know where to remove the outline from:
jQuery('body').mousemove(function (e) {
var el = e.target;
$('.outline').removeClass('outline'); //remove outline
jQuery(el).addClass('outline'); // add outline
});
CSS:
.outline {
outline: solid 2px #000;
}
Demo: http://jsfiddle.net/maniator/UQhVE/
Upvotes: 1