1

I have a very annoying problem. I have a button called #log-outand when you click it it saves a certain peice of data in a localStorage variable called importantOSdata.

When the page loads it checks if the variable != null and if it isn't removes the div that was saved in the localstorage variable from the page and replaces it with the one that IS saved in the localStorage variable. The problem is as the title says, jquery events will not work on the dynamic divs even though they already worked when there was no saved data and it was just plain hardcoded html. I have tried using .on() but as you can see in the code I use the this keyword and will not work properly. I MUST use the this keyword.

(1)The code I have has a click event for the div and checks if it has a certain type of data- tag (data-title) and a plain old src tag. This is then passed into a function which creates a popup iframe with src from the src tag. (1)The code that used to work:

$(".icon").each(function() {
   var iconFile = $(this).attr("data-iconFile");
   var title = $(this).attr("data-title");
   var file = $(this).attr("src");
   $(this).css("backgroundImage", "url(" + iconFile + ")");
   $(this).dblclick(function() {
        new createFrame(file,title);
        addItem($(this).attr("class"),iconFile);
        //canSlideUp = false;
   });
});

The new code I've tried:

$(".icon").each(function() {
            var iconFile = $(this).attr("data-iconFile");
            var title = $(this).attr("data-title");
            var file = $(this).attr("src");
            $(this).css("backgroundImage", "url(" + iconFile + ")");
                $(this).on("dblclick",function() {
                    new createFrame(file,title);
                    addItem($(this).attr("class"),iconFile);
                    //canSlideUp = false;
                });
            });
        });

And the save/load code:

$(document).ready(function() {
    $("#log-out").click(function() {
        alert("Your Progress was saved:"+localStorage.getItem("inportantOSdata"));
        localStorage.setItem("inportantOSdata",document.getElementById("data-holder").innerHTML);
    });
});
window.onload  = function (){
    if(localStorage.getItem("inportantOSdata") != null) {
        $("#data").remove();
        alert("data exists");
        $("#data-holder").html(localStorage.getItem("inportantOSdata"));
    }
}
//localStorage.clear();

You can see how I use the this keyword. ANy ides an this interesting problem? Thanks in advanced!

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • 1
    You need to use `on` in the [Event Delegation](https://learn.jquery.com/events/event-delegation/) method. Your `on` should look something like this: `$(document).on('click', '.icon', .function() {...do stuff...}` - see also this post: http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on - NOTE that your `.each` isn't going to work either on dynamically created elements. They won't exists when the .each runs. – random_user_name Nov 28 '15 at 21:36

1 Answers1

0

Remember, You can bind the click event to the container inside which you are dynamically adding elements.

So lets say the container is #container.

You can bind the event to its children using

$("#container").on('click', ".xyz" ,function(){
  // good to go.
  // $(this). gives you the handle to each element individually.
});

How It works:- Even if the subject element were not present at the time of the execution of this script, it will still work just fine. Because..

When you bind a .click() event on a specific element then jQuery shall check for all the matching elements and bind the event on the first execution, but if the element was added later on, then there is no event bound to it.

But When you bind the events to the container and limit its scope to a specific .class or #id, then every time the container registers a click, jQuery checks for that respective element (.xyz in our case) within the container and the event is fired in relation to the container and not the element itself, so existence of the subject element doesn't really matter at the time of execution of the script.

Note:- While this technique is handy, care must be taken to bind the event to the nearest parent container, since this method once invoked has to traverse through the DOM to find all the matching elements. And this can prove a performance hazard once enough complex DOM is provided or the no of dynamically added elements reach a substantial amount(limited by the client processing power). So something like $(document).on('click', #xyz ,function(){}); is a strict no no.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88