简体   繁体   中英

help with understanding the logic behind how javascript executes on new dom elements being created on the fly

I have a this set up

<ul>
<li>item 1</li>
</ul>

my js let me make them sortable and what not, one feature I have is that via ajax i can create a new list item on the fly. But whats interesting is that I have a hoverIntent letting me hover over the list item and a delete and edit icon appears letting me perform the intended actions.

My problem is that when I make a new list item on the fly the hoverIntent isn't applied to it. The code created is identical to the other list items, I know it works because when I refresh the page and reload the js then the hoverIntent kicks in and applies the hover effects to the new items created.

None of this works on the fly tho, how can I make this work?

my js for creating a new list item is:

var timestamp = 0;
    $('.new-group').click(function(e){

        // Only one group per 5 seconds is allowed:
        if((new Date()).getTime() - timestamp < 5000) return false;

        $.get("resources/ajax/groups.ajax.php",{
            action :'new',
            uid     : uid,
            text   :'New Group, Doubleclick to Edit.'
        },function(data){
            $(data).hide().appendTo('.grouplist').fadeIn();
            //GROUP.find(".groups-action-div").show('slow');
        });
        timestamp = (new Date()).getTime();
        e.preventDefault();
    });

I'm betting that in my success function is where I can make this work,

you can log in and see my problem at www.helixagent.com with login as test/password go into the Contacts tabs and click on the + icon to make a new group

hoverIntent loads the effect on page load, meaning that when you create a new element, you've already executed the hoverIntent aspects, and it doesn't apply to the newly create element.

Basically, you just have to run hoverIntent again

I haven't tested it, but you'd need to do something like this:

var timestamp = 0;
$('.new-group').click(function(e){

    // Only one group per 5 seconds is allowed:
    if((new Date()).getTime() - timestamp < 5000) return false;

    $.get("resources/ajax/groups.ajax.php",{
        action :'new',
        uid     : uid,
        text   :'New Group, Doubleclick to Edit.'
    },function(data){
        $(data).hide().appendTo('.grouplist').fadeIn();
        //GROUP.find(".groups-action-div").show('slow');
    });
    timestamp = (new Date()).getTime();
    e.preventDefault();


    var config_names = {
        over: show_delete_names,
        timeout: 200,
        out: hide_delete_names
    };
    $(".contactlist li:last-child").hoverIntent( config_names );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM