0

I have a dynamically loaded page with divs of class product. Jquery doesn't see this class with the code below. When I click on product divs it doesn't do anything. However clicl on nav-element works fine. Any way to make it work with it?

$(document).ready(function(){
$(".nav-element").click(function(){
    var id = $(this).attr('id');
    alert(id);
    $(".nav-element").css("background", "#fff");
    $("#"+id).css("background", "#A4CFBE");
    $(".content-white").load(id+".html");
    });
    $(".content-white").load("nav-element1.html");
$(".product").click(function(){
    alert("poop");
})
}); 

2 Answers 2

4

a dynamically loaded page with divs of class product

You need to use Event Delegation. You have to use .on() using delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Ideally you should replace document with closest static container. Here its ".content-white"

Example

$(".content-white").on('click', '.product', function () {
    alert("poop");
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try a delegated event handler

$(document).ready(function () {
    $(".nav-element").click(function () {
        var id = $(this).attr('id');
        alert(id);
        $(".nav-element").css("background", "#fff");
        $("#" + id).css("background", "#A4CFBE");
        $(".content-white").load(id + ".html");
    });
    $(".content-white").load("nav-element1.html");

    // event delegation to the closest static element
    $(".content-white").on('click', ".product", function () {
        alert("poop");
    });
});

2 Comments

Accepted because adeneo answered first.
@user1380398 - Actually, Satpal posted an answer first, but it was just a general "use delegation" answer, I posted the first answer with working code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.