Live addEventListener mouseenter

I have jQuery code:

$(document).on("mouseenter","a",function(e){
    //...
});

How to create the same, but with native JavaScript (without jQuery)?

I only need compatible with Chrome.

+3
source share
2 answers

For the same function, where you can add multiple event listeners to a single element, use the following:

addEventListener('mouseover', function(e) {
    if (e.target instanceof HTMLAnchorElement) {
        //...
    }
});

This will do the same. For other selectors:

addEventListener('mouseover', function(e) {
    if (e.target instanceof HTMLAnchorElement) {
        //matches if the element is an <a>
    }
    if (e.target.className.match(/(\s|^)foobar(\s|$)/)) {
        //matches if the element has the class "foobar" in its classes list
    }
    if (e.target.id == 'baz') {
        //matches if the element has an id of "baz"
        //same syntax works for attributes like 'name', 'href', 'title', etc.
    }
    if (e.target instanceof HTMLLabelElement && e.target.attributes.for.value == 'baz') {
        //matches a <label> tag that has its 'for' attribute set to 'baz'
        //the element.attributes.attrName.value is the syntax for getting the value
        //    of any attribute that isn't available otherwise
    }
});

mouseenter , , , , . , mouseenter , , jQuery, document , . , , mouseover.

+4

.

Live Demo

var links = document.links || document.anchors || document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    addEvent(links[i], 'mouseenter', action);
}

function addEvent(element, myEvent, fnc) {
    return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false));
}

function action(evt) {
    var e = evt || window.event,
        link = (e.currentTarget) ? e.currentTarget : e.srcElement;
    link.style.color = "lime";
}
0

All Articles