Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onmouseover running multiple times while hovering on element?

Why does onmouseover run multiple times while I hover over one element?

I'm trying to run a simple animation when the user hovers over an icon but it runs multiple times.

I'm testing it here:

http://lujanventas.com/test.php

Anyway, any ideas on how to fix it? maybe using a listener instead?

This is the javascript running onmouseover:

function upIcon(n) {
    console.log("Mouseover icon: " + n);
    $('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 );
    $('#icon' + n).animate({ backgroundPositionY : "+=15px" }, 200 );
    }
like image 799
lisovaccaro Avatar asked Feb 22 '12 00:02

lisovaccaro


People also ask

What is difference between Mouseenter () and mouseover () event?

The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element.

What is mouseover and Mouseout?

The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves. These events are special, because they have property relatedTarget . This property complements target . When a mouse leaves one element for another, one of them becomes target , and the other one – relatedTarget .

What does onmouseover do in HTML?

The onmouseover attribute fires when the mouse pointer moves over an element. Tip: The onmouseover attribute is often used together with the onmouseout attribute.


1 Answers

Try using mouseenter and mouseleave instead of mouseover and mouseout. The former fires only when the cursor enters the region of the element and the latter fires when the cursor moves between descendants as well.

I added this code to your page via my console and it worked as expected:

//bind an event handler to each nav element for the mouseenter event
$('.categoryButtons').children().bind('mouseenter', function () {

    //call the `upIcon` function with the index of the current element
    upIcon(($(this).index() + 1));
});

I also removed the inline onmouseover code for each nav item.

Update

You can use your existing function a bit differently and not use the anonymous function for your event handler (notice the function chaining to avoid duplicate selections):

function upIcon(event) {
    var n = ($(this).index() + 1);
    $('#icon' + n).animate({ backgroundPositionY : "-=15px" }, 200 ).animate({ backgroundPositionY : "+=15px" }, 200 );
}

$('.categoryButtons').children().bind('mouseenter', upIcon);

When you reference an existing function as the event handler, it gets passed the event object like any other event handler and you can also use this to refer to the element on which the event was triggered.

like image 110
Jasper Avatar answered Oct 14 '22 21:10

Jasper