How to execute a function when the mouse is on a certain element?

2

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

    
asked by anonymous 06.10.2014 / 23:42

1 answer

5

This functionality you want is achieved with an event sink.

Having a selector to select the element can add a dropper. That is:

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

Then this minhaFuncao will have the event as an argument.

Example: link

If you want to have more than one element with this functionality you will have to loop through and apply this to each one.

For example:

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

Example online: link

If you use a library like MooTools or jQuery, this is simpler. There you can do respectively:

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

The advantage is that it gets easier to write, the downside is that it gets a bit slower and heavier for the computer / mobile than running the code.

It is worth mentioning that in some cases it may be better to use only CSS rather than JavaScript. For example to make the background color change does not require JavaScript, CSS would suffice:

div:hover{
    color: #ccf;
}

Example: link

    
06.10.2014 / 23:54