Alexander Vovolka
Alexander Vovolka

Reputation: 53

How to add mouseenter event for dynamically added element with native JS

for some reason, I need to use native JS instead of jQuery. I need to add an event to dynamically added element. I did it with jQuery but can't do with native JS.

Here is my code with jQuery

$('body').on('mouseenter', '.password_link', function(){
...
});

Here what I tried with JS

document.querySelector('body').addEventListener('mouseenter', function(){
   var forgotPasslink = document.getElementsByClassname('password_link');
   if( e.target == forgotPasslink[0] ){
      ...
   }
});

but it's not working. I tried to google but without success.

Upvotes: 2

Views: 1495

Answers (4)

user2356433
user2356433

Reputation: 91

Well if you are using this on a static content, I mean, not over ajax loaded content you cand use this:

    var elements = var x = document.getElementsByClassName("password_link");
    if(elements.length>0){
        for(var i =0; i< elements.length; i++){
            elements[i].addEventListener('mouseover', function(element){
                //And Here is where you magic Code goes!
            });
        }
    }

Enjoy!!!

Upvotes: 0

LoneRanger
LoneRanger

Reputation: 117

Do like this,

var item = document.getElementsByTagName("BODY")[0];
    item.addEventListener("mouseover", func, false);
    item.addEventListener("mouseout", func1, false);

    //mouse enter
    function func()
    {   var forgotPasslink = document.getElementsByClassname('password_link');
       if( e.target == forgotPasslink[0] ){
          //your code
       }
    }

    //mouse leave

    function func1()
    {  
    //your code
    }

Upvotes: 0

Neelesh
Neelesh

Reputation: 736

Use mouseover for example :-

document.addEventListener('mouseover', function (e) {
    if ((e.target.className =='test')) {
      console.log("Got here");
    } else  {
      // do nothing.
    }
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="test">
  Sample Test 
  </div>

Upvotes: 2

Sooraj
Sooraj

Reputation: 10567

You have to use mouseover , this should work

document.addEventListener('mouseover', function (e) {
    if (hasClass(e.target, 'password_link')) {

        //your code
    } else  {

        // your code
    }
}, false);

Upvotes: 0

Related Questions