Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click event handlers don't work after loading html page with load()

Hi I am loading several html pages on an index page depending on what link was clicked.I have a problem with the links that have asocietted click event handlers.It seems that after the jQuery loads the html file the links in that html do not have there click event handlers binded to them. Here is my code:

This is the html for one of the links that does not work:

<a href="#" id="NavContactPage" data-sectionId="Skills">skills</a>

This is the jquery code asocieted with it:

$("nav a , a.first_anchor , a#NavContactPage").click(function(){
    var id = $(this).attr("data-sectionId");
    var link = "load/" + id + ".html";

    $("div#Content").load(link , function(){
        $("section#" + id).fadeIn(); 
        if(id === "Portfolio"){
            $('div.slide').cycle('fade');
        }
        if(id === "Home"){
            $("#jcycleslider").cycle({
                fx: mtransition,
                easing: easing,
                before: onBefore,
                after: onAfter,
                speed: mpace,
                timeout: mnext,
                sync: msync,
                randomizeEffects:0,
                pager:'#jslider_nav'
            })
            $("#jslider_nav a").text("");
        }    
    })      
    return false;
})

How can I solve this problem?

like image 843
Nistor Alexandru Avatar asked Jan 15 '13 13:01

Nistor Alexandru


1 Answers

$("selector").click(...) only registers the callbacks for the click event to the elements that where visible to jQuery at the time you did the query. So for newly added elements, that match this selector, the callback will not be applied.

You either need to registrate the callbacks to the newly added elements again or you need to use:

$(document).on('click',"nav a , a.first_anchor , a#NavContactPage", ... );

Instead of using document as root it is recommend to use e.g. the element where you are loading the content to as root e.g. $("div#Content").on( .... );

like image 62
t.niese Avatar answered Oct 15 '22 22:10

t.niese