anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

on scroll event not binding for dynamically added elements Jquery

I am dynamically adding a <div> element with class name requirement, what I want to achieve is to execute my functionality when a scroll event happens inside of this div.

HTML

<div class="scroll requirement" >

jQuery

$(document).on('scroll','.requirement',function(){alert("hello")});

Upvotes: 1

Views: 1198

Answers (1)

kurt
kurt

Reputation: 1156

This is quite strange, I guess its because the event can fire so often. It works if it is rebound upon creation...

$(document).ready(function(){
	$('#add').click(function(){
      $('body').append('<div class="scroll requirement" ><br><br><br><br><br><br><br><br><br><br><br><br><br></div>');
      $('.requirement').on('scroll',function(){alert("hello")});
    });
 });
/*.pane{
    min-height:2000px;
    min-height:400px;
   
}
.requirement{
    max-height:100px;
     overflow:scroll;
}
}*/

		body{ font-family: tahoma; font-size: 12px; }
	div.requirement{
		height: 90px;
		width: 300px;
		border: 1px solid;
		background-color: lavender;
		overflow: auto;
	}
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
<body>
<div class="scroll requirement" >
<br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<button id="add">Add another pane</button>
  </body>
  </html>

Inline binding however works...

$(document).ready(function(){
	$('#add').click(function(){
      $('body').append('<div class="scroll requirement" onscroll="scrollHandler()" ><br><br><br><br><br><br><br><br><br><br><br><br><br></div>');
    //  $('.requirement').on('scroll',function(){alert("hello")});
    });

 });
    function scrollHandler(){
    alert('hello');
    }
/*.pane{
    min-height:2000px;
    min-height:400px;
   
}
.requirement{
    max-height:100px;
     overflow:scroll;
}
}*/

		body{ font-family: tahoma; font-size: 12px; }
	div.requirement{
		height: 90px;
		width: 300px;
		border: 1px solid;
		background-color: lavender;
		overflow: auto;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="scroll requirement" onscroll="scrollHandler()" >
<br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>

<button id="add">Add another pane</button>
  </body>

Upvotes: 1

Related Questions