Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding jquery to dynamically loaded content

Tags:

jquery

I have the following html tree :

<div class="section yellow" id="section1">
    <div id="content-wrap1" class="content-wrap">
</div>

I am using ajax to load the following content into #content-wrap1:

<div id="content">
    <a href="whoweare.php">Who we are</a>
    <a href="whatwedo.php">Our team</a>
    <p>ABOUT US : Dance is a type of art</p>
</div>

which happens successfully, and the resulting HTML looks like this :

<div class="section yellow" id="section1">
    <div id="content-wrap1" class="content-wrap">.
        <div id="content">
        <a href="whoweare.php">Who we are</a>
        <a href="whatwedo.php">Our team</a>
        <p>ABOUT US : Dance is a type of art</p>
    </div>
</div>

Now I want to click on the dynamically loaded link to load the following content :

<div id="content">
    <a href="whoweare.php">Who we are</a>
    <a href="whatwedo.php">Our team</a>
    <p>Hi there! How are you?</p>
</div>

so that the final HTML looks like this :

<div class="section yellow" id="section1">
    <div id="content-wrap1" class="content-wrap">.
        <div id="content">
        <a href="whoweare.php">Who we are</a>
        <a href="whatwedo.php">Our team</a>
        <p>Hi there! How are you?</p>
    </div>
</div>

I have heard that I should use on() to bind jquery to a dynamically loaded content. So I do the following:

('#section1').on("click", "#section1#content-wrap1#content a", function(){
    alert("1");
    toLoad = $(this).attr('href')+' #content';
    $('content-wrap1').load(toLoad);
}

Ques1: Is this the correct usage of on() ? Because when I click the link, I don't get alert 1 on the screen and the page simply navigates to whoweare.php

Ques2: Incase I do manage to get the alert, is it possible theoritically to click on a link that loads content that replaces the link clicked in the first place ?

like image 333
soundswaste Avatar asked May 20 '26 21:05

soundswaste


1 Answers

Ques1: Is this the correct usage of on() ? Because when I click the link, I don't get alert 1 on the screen and the page simply navigates to whoweare.php

  • you are missing a dollar sign: $ and use document you are binding same id on same id which is not correct, further if you keen: What is the meaning of "$" sign in javascript & If you are more keen to know why .on What's wrong with the jQuery live method?

Code

$(document).on("click", "#content a", function(){
        alert("1");
        toLoad = $(this).attr('href')+' #content';
        $('content-wrap1').load(toLoad);
})

Ques2: Incase I do manage to get the alert, is it possible theoritically to click on a link that loads content that replaces the link clicked in the first place ?

  • this might help you out: jQuery how to replace src url
like image 89
Tats_innit Avatar answered May 22 '26 11:05

Tats_innit