Frage

I have jQuery's code:

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

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

I need only Chrome compatible.

War es hilfreich?

Lösung

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

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

That will do the exact 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
    }
});

The problem with delegating the mouseenter event though is that it only fires when the element it is applied to is hovered over. In other words, if you attach a mouseenter event to the document, like in your jQuery code, it will only fire when the document is entered with the mouse, but not for any of the children. For making it work on the children, you'll need to use mouseover.

Andere Tipps

This optimizes compatibility across old and new browsers.

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";
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top