Is it good practice to do $ ("*"). Live ("mouseover", someFun) in jQuery?

Sometimes there will be many mouse hover events and the $ ("*") selector can be expensive. Will this slow down my pages when crawling on slow IE6 machines?

Is there a better way to do this? I want to know about every mouseover event that happens on the page.

+2


source to share


2 answers


Just do it $('body')

. This will assign one handler to the element <body>

, and every child element (so every element on the page) will bubble that mouseover event up to that point. All you need to do inside the handler is check the event maker to find the exact element:

$('body').mouseover(function(e) {
    var sender = e.target;
    //sender is the element who was moused over
});

      



The key is not to do anything too intense inside this handler, as it will basically fire constantly when the user moves the mouse over your page. It is best to start by checking the most restrictive conditions and returning from the method as often as possible.

+4


source


I'm going to go to a limb here and say that judging from the way that expression makes my teeth ache, it might actually be bad practice.



But if you absolutely must be aware of every mouse hover, this might be the best available. I would, however, ask a question about the perceived need and suggest that the goals you think will be fulfilled for you can be achieved in an excellent way.

+3


source







All Articles