How to execute a function when the mouse is over a given element?

Asked

Viewed 7,046 times

2

How to create a generic javascript function that runs only on the element the mouse is currently on top of?

1 answer

5


This functionality you want is achieved with an event receiver.

Having a selector to select the element you can add a headphone to it. That is to say:

var elemento = document.querySelector('div'); // escolher o elemento
elemento.addEventListener('mouseover', minhaFuncao); // adicionar o oscultador

There’s that one minhaFuncao will have as argument the event.

Example: http://jsfiddle.net/cyaj6g26/

If you want to have more than one element with this functionality you will have to cycle and apply this earpiece to each of them.

For example:

var elementos = document.querySelectorAll('div');
for (var i = 0; i < elementos.length; i++) {
    elementos[i].addEventListener('mouseover', minhaFuncao);
}

Online example: http://jsfiddle.net/cyaj6g26/1/

If you use a library like Mootools or jQuery it becomes simpler. Then you can do it respectively:

$$('div').addEvent('mouseover', minhaFuncao); // MooTools
$('div').on('mouseover', minhaFuncao); // jQuery

The advantage is that it is easier to write, the disadvantage is that it gets a little slower and heavier for the computer/mobile that is to run the code.


It is worth mentioning that in some cases it may be better to use only CSS and not Javascript. For example to make the background color change is not necessary Javascript, CSS would suffice:

div:hover{
    color: #ccf;
}

Example: http://jsfiddle.net/cyaj6g26/2/

  • 1

    I think in Portuguese it says Listener same :P

  • @brasofilo: "up"-ado :)

  • 2

    Real case, back in Braza playground was so beaten that the construction companies decided to call fun floor. Fictitious case, "-But how do you say it in Portuguese? -Ah, I think it’s plaigroundi".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.