How to create a generic javascript function that runs only on the element the mouse is currently on?
How to create a generic javascript function that runs only on the element the mouse is currently on?
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.
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);
}
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;
}