Reputation: 9221
I met some basic problem in jquery, but I can't figure it out.
Here is the code: http://jsfiddle.net/pdQsY/
How do I get the position of half of a div.(mouseover left 200px of the div, output font color #ff0
. mouseover right 200px of the div, output font color #336)
I use e.pageX - div.offsetLeft
, but this echo NaN
, thanks.
Upvotes: 1
Views: 392
Reputation: 349042
Use .offset().left
instead of the non-existent jQuery property offsetLeft
.
For efficiency considerations, you should cache the $("#main")
and $('p')
variable. You're calling this twice in your mousemove
handler. The mousemove
handler is fired very often, so you end up calling $("#main")
over thousand times, easily.
var $main = $("#main");
var $p = $('p');
$main.mousemove(function(e) {
var mouseX = e.pageX;
var offsetLeft = $main.offset().left;
if(mouseX < 200 + offsetLeft){
$p.css('color','#ff0');
} else {
$p.css('color','#336');
}
$p.html(mouseX - offsetLeft);
e.preventDefault();
});
Upvotes: 4