user3514875
user3514875

Reputation: 3

jQuery - Call function in function with dynamic content (.load())

I have a site in which content is dynamic loaded via jQuery .load(). Sadly, I can't catch an event from the dynamic loaded content even though using .on().

This is my function in which I can't trigger the $("#control_right").on('click')-function after loading changeContent(2):

function changeContent(step){
$('#content').toggle(100);
setTimeout(function() {
      $('#content').load("template/step_" + step + ".html");
}, 180);
$('#content').delay(300).toggle(200).queue(function(){

    if(step === 1){ // IF STEP 1. CHOOSE MALE OR FEMALE
        console.log("step1");
        $("#choice_man").on('click', function(){
            changeContent(2);
        });

        $("#choice_woman").on('click', function(){
            changeContent(2);
        });
    }

    if(step === 2){ // IF STEP 2. Do something else
        $("#control_right").on('click', function() {
            console.log("CLICK");
        });
    }
});
}

I hope my problem is understandable.

Upvotes: 0

Views: 201

Answers (2)

bipen
bipen

Reputation: 36551

like many other answer in stackoverflow (please search before posting your question), you have to use on delegated event and not just on().

 $('#content').on('click', "#choice_man",function(){
       ...

delegating it to your closest static parent present in the document at the time of insertion is preferred rather than document itself performancewise

Upvotes: 1

Justinas
Justinas

Reputation: 43565

Try changing selector to one from DOM elements:

$(document).on('click', '#control_right', function(){...})

Bdw, why are you using .delay(300).toggle(200)?

.load('url.html #loadContentFrom', function(){/* Callback function */})

Upvotes: 2

Related Questions