-1

I am testing out some functionality and I am trying to make so once I hover on a particular element (in this example any link) it will output something inside the console.

I have looked at this answer -> here where it says "you can define your function once, and it will execute for any dynamically added elements"

So I have this js script but once the elements are loaded dynamically, i.e. like youtube videos, but once I hover on the newly added elements, this script will not work, no output inside the console.

$( "a" ).on({
  click: function() {
    console.log('clicked');
  }, mouseenter: function() {
   console.log('enter');
  }, mouseleave: function() {
    console.log('left');
  }
});

Am I missing something here?

AlwaysConfused
  • 729
  • 2
  • 12
  • 37
  • 1
    "Am I missing something here?" Yes, [you're missing the delegate parameter (`[selector]` in the docs)](http://api.jquery.com/on/). – zzzzBov Jun 19 '17 at 22:59

1 Answers1

1

The way you have bound the elements is used to bind multiple event handlers to the same elements. If they are dynamically added then you will have to resort to event delegation. Where you will be binding the event to a parent element which is present when the event is bound.

$( "body" ).on('click', 'a', function() {
    console.log('clicked');
});

$( "body" ).on('mouseenter', 'a', function() {
    console.log('enter');
});

$( "body" ).on('mouseleave', 'a', function() {
    console.log('left');
});

you can replace the body with any other closest parent to a which is present at the time of event binding.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • 1
    `$('body').on({...events...}, 'a')` is the way to bind multiple listeners to the same delegate. – zzzzBov Jun 19 '17 at 23:05
  • Hmm..I just used the example from the [official docs](http://api.jquery.com/on/#example-8), but I must used the wrong approach.. Your example works exactly as I was trying to make, thanks! – AlwaysConfused Jun 19 '17 at 23:08
  • The only problem is that the element is getting triggered multiple times for some reason... – AlwaysConfused Jun 19 '17 at 23:37
  • @AlwaysConfused Just make sure that you are not binding events to the same element multiple times – Sushanth -- Jun 20 '17 at 00:27
  • @Sushanth-- I used your sample to test it out and if the website page is loaded with ajax, it will somehow output 3 or 4 values in the console when I hover once on the element.. – AlwaysConfused Jun 20 '17 at 11:42