Piyush Kumar Baliyan
Piyush Kumar Baliyan

Reputation: 404

Run javascript on dynamically loaded content for ajax based website

I an currently designing a ajax based navigation website. The problem I encountered is when I try to run jquery on dynamically loaded content it doesn't work.

Here is what I did:

index.html

<html>
<head>
    <title>Testing Dynamic Content</title>
    <link href="style.css" rel="stylesheet"/>
    <script src="http://localhost/jquery.js"></script>
    <script src="main.js"></script>
</head>
<body>
    <div class="main">
        <div class="content">
            <ul class="list">
                <li>One</li>
                <li>Two</li>
                <li>Three</li>
                <li>Four</li>
            </ul>
        </div>
    </div>
    <script>
    $('.list').greenify();
    </script>
</body>
</html>

2.html

<html>
<head>
    <title>Testing Dynamic Content</title>
    <link href="style.css" rel="stylesheet"/>
    <script src="http://localhost/jquery.js"></script>
    <script src="main.js"></script>
</head>
<body>
    <div class="main">
        <div class="content">
            <span id="hello">Content</span>
        </div>
    </div>
    <script>
    $('#hello').on('click',function(){
        $('.main').load('index.html .content');
        $('.list').greenify();
    });

    </script>
</body>
</html>

style.css

.list{
    color:#f00;
}

main.js

$.fn.greenify = function() {
    this.css( "color", "red" );
};

The problem is in the $('list').greenify();. When I load content of index.html on 2.html using .load() the content loads in red color as defined in css. When I run $('list').greenify() on this loaded content it doesn't works.

How can I run mak this happen to run JavaScript on dynamically loaded content?

I need to do this to make a slideshow run on dynamically loaded webpage. And slideshow is not working.

Upvotes: 0

Views: 4157

Answers (2)

Hoja
Hoja

Reputation: 1207

You should bind the events like this then only your script will affect on dynamic DOM elements

 $('body').on('click','#hello',function(){
        $('.main').load('index.html .content');
        $('.list').greenify();
});

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28588

issue is your code run before your page successfully loaded, move your code to document ready event:

$(document).ready(function(){
   $('.list').greenify();
})

and jQuery load is async you need to run your javascript in success function

$('.main').load('index.html .content', function() {
    //will execute when load successfully
    $('.list').greenify();
});

Upvotes: 3

Related Questions