The title of this question reflects the final goal, which is preventing .hover()
to be bind more than once to the same element.
Before asking I did a search on SO and I have found this question which is already answered: Checking if jQuery .hover action is already binded
Also I've Googled a lot about it and it looks like the accepted answer to that question is correct.
With that, I came up with a small piece of code which tries to do the following:
- Loop over all elements with a class
class-name
- Obtain all the events on that element
- Check if the
.hover()
event is already bind on it - If it's not, then add it.
$(document).ready(function() {
$('.class-name').each(function() {
var events = $._data($(this)[0], 'events');
if ( !(events['mouseover'] && events['mouseout']) ) {
$(this).hover(
function() { alert('IN'); },
function() { alert('OUT'); }
);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<a class="class-name">a</a>
The code above doesn't work and I cannot figure out where the error is. According to the JS console output, the events
variable is undefined
.
Any help appreciated. Thanks.