0

I have following code:

$('body').on('mouseenter', 'label', function(){
        if(this.offsetWidth < this.scrollWidth){
            if(!this.getAttribute('title')) {
                this.setAttribute('title', this.innerHTML);
            }
        }
        else{
            this.removeAttribute('title');
        }
    });

But in my project we need to have less dependencies with jquery. So i need to rewrite on('mouseenter') method. I tried something like this:

var matches;

    (function (doc) {
        matches =
                doc.matchesSelector ||
                doc.webkitMatchesSelector ||
                doc.mozMatchesSelector ||
                doc.oMatchesSelector ||
                doc.msMatchesSelector;
    })(document.documentElement);

    document.addEventListener('mouseenter', function (e) {
        if (matches.call(e.target, 'label')) {
            if (this.offsetWidth < this.scrollWidth) {
                if (!this.getAttribute('title')) {
                    this.setAttribute('title', this.innerHTML);
                }
            }
            else {
                this.removeAttribute('title');
            }
        }
    }, false);

But it doesn't work, cause it firing only once ( on mouseenter on document ). I can't get all elements with tag label and add event listener to them, cause i have many labels in different parts of my application. Is this possible to get full equivalent of jquery function?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ya_hen
  • 3
  • 3
  • 1
    *"convert jquery.on('mouseenter') to javascript"* It *is* JavaScript. You mean you want to convert it to use the DOM API instead of jQuery's API. – T.J. Crowder Sep 29 '14 at 10:02
  • this isn't a simple conversion as event-delegation is involved which involves a lot of code.. – Amit Joki Sep 29 '14 at 10:03
  • You are going to make a rod for your own back with this. Why not use a DOM-specific microJS library instead like: http://webpro.github.io/DOMtastic/ (found on microjs.com) – Andy Sep 29 '14 at 10:09
  • yes, sorry, i mean DOM API – ya_hen Sep 29 '14 at 10:38
  • so i need to know, is it possible to write this in DOM API without any libs? – ya_hen Sep 29 '14 at 10:39
  • @user2767545 those libraries are using `DOM` API only. Go under the hood and grab your stuff.. you have the code without any *library*.. what a miracle..! – T J Sep 29 '14 at 16:39
  • Thanks for your responses, i found what i need [here](http://stackoverflow.com/questions/23508221/vanilla-javascript-event-delegation) – ya_hen Sep 30 '14 at 07:15

1 Answers1

0

You could use mouseover instead and change the first line inside the event-callback, so var matchescan be omitted:

document.addEventListener('mouseover', function (e) {
    if (e.target.tagName.toLowerCase() == 'label') {

    /* rest of your code */

}, false);
Martin Ernst
  • 3,199
  • 1
  • 12
  • 12