0

first let me say i have seen this post.

which says (as does api.jquery.com) that the .live() and .on() let you assign a jquery event, which applies even to future elements. however my following jquery:

    $("#playerImg").on("mouseenter",function () {
        console.log("works");});

works at the start but after i run this code:

function move(moveTo) {
   document.getElementById(player.currentLocation).innerHTML = "";
      player.currentLocation = moveTo;
   document.getElementById(player.currentLocation).innerHTML += player.displayText;
}

here are relevant variables

var player = {
    "displayText" : "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
        id='playerImg' "class='onTop' alt='you' border='0' />",

   "currentLocation": 0 //(i use a 5 * 5 table with id's 0-24)
}

the above code doesnt run. how can i make an event in jquery, which can run on elements that dont exist yet?

link here

Community
  • 1
  • 1
Math chiller
  • 4,123
  • 6
  • 28
  • 44
  • Take a look at the accepted answer on this post: http://stackoverflow.com/questions/9944499/how-to-dynamically-rebind-jquery-objects Hope that helps. – David Tansey Aug 30 '13 at 23:01
  • You're using a direct event, and you need to use a delegated event, meaning you attach to a container that contains whatever you actually want to attach the handler to. See the [Direct and delegated events section](http://api.jquery.com/on/) for on() – ernie Aug 30 '13 at 23:01

1 Answers1

5

Using .on() like you do apply direct event, which are faster but DOESN'T apply to dynamic elements.

You need to use .on() like that for dynamic elements :

$(document).on("mouseenter", '#playerImg',function () {
    console.log("works");
});

document should be the closest static element for performance gain.

Side note, id's must be unique, change it for class. The code above may not work because it use an id. If it's the case and you don't want to change for whatever reason, use this :

$(document).on("mouseenter", 'img#playerImg',function () {
    console.log("works");
});
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75