0

few of div elements are generated using ajax and few are static. The jquery is working only on static elements not on dynamic generated html. I am running a jquery on clicking any element of "app" class. But the jquery is only working on static html not on the dynamically html

<!Doctype html>
<html>
<head>
<title>applications</title>
<link rel="stylesheet" type="text/css" href="css/style.css">

<script src="//code.jquery.com/jquery-1.7.2.min.js"></script>

<script>

$(document).ready(function(){
$.ajax({
        type:'GET', 
        url:'application/show_app.php',
        data:{show_app:"1"}, 
        success: function(data){
            if(data)
            {
                var split= data.split('%%%%');
                for(var i=0;i<split.length-1;i++)
                {
                    var div= document.createElement("div");
                    var div_child=document.getElementById("app_row").appendChild(div);
                    div_child.className="app";
                    div_child.innerHTML="dynamic";    //dynamically generated                   

                 }

             }
        }, 
        failure: function(){
            alert(failed);
        }

    }) ;

$(".app").click(function(){
    alert("jquery"); //jquery which will run on clicking the division

});






});

</script>





</head>
<body id="default" class="full">           //basic html
    <div class="header">
        <h1>
        <a title="urban airship">urbanairship</a>
        </h1>
    </div>
    <div class="main" name="application-main">
        <div class="sub-header">
            <h2>Your Applications</h2>
            <div class="sub-header-actions">
                <a href="application/add_app.php/">
                    <span class="sprite plus-ico"></span>
                    New App
                </a>
            </div>
        </div>
        <div class="row main-app-list" id="app_row">
    <div class="app">static</div> //static html


        </div>
    </div>



</body>
</html>
nitin
  • 3
  • 8
  • use $(document).on("click",".app",function(){ – Anoop Joshi P Jun 16 '14 at 07:40
  • The reason to work jquery with static content is they are known to DOM, and can handle the events of known elements. but with dynamic contents you have to bind the event with that element by using .bind(), or you can .live()- it is deprecated, so you can use .on() to function it properly. – Pramod Jun 16 '14 at 07:45

1 Answers1

3

Try:

$(document).on('click', '.app' , function(){
    alert("jquery"); //jquery which will run on clicking the division
});

This works because your event listener is now attached to the document and not the individual elements. This allows elements that are loaded in via AJAX to still fire events. You should also look at scoping the on i.e. $("#myWrapper").on(...) as this is better for performance.

See documentation: JQuery On

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
Mr_Green
  • 40,727
  • 45
  • 159
  • 271