i have a problem that javascript script only loaded once when the page is loading,but i need it every time i get data from WebMethod on the server side
here is my code:
My JavaSript ajax:
<script type="text/javascript">
$(document).ready(function () {
function InfiniteScroll() {
$('#divPostsLoader').html('<img src="img/loader.gif">');
$.ajax({
type: "POST",
url: "Home.aspx/GetLastArticles",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
$('#divPostsLoader:last').after(data.d);
}
$('#divPostsLoader').empty();
},
error: function (data) {
if (!document.getElementById('#divPostsLoader').innerHTML == "<p>END OF POSTS</p>")
$('#divPostsLoader').empty();
$('#divPostsLoader').html("<p>END OF POSTS</p>");
}
})
};
var b = false;
//When scroll down, the scroller is at the bottom with the function below and fire the lastPostFunc function
$(window).scroll(function () {
if ($(document).height() <= $(window).scrollTop() + $(window).height()) {
InfiniteScroll();
}
b = true;
});
if (!b) {
window.onload = function () {
InfiniteScroll();
};
}
});
</script>
and here is my javasript that i want it to fire everytime i get data from GetLastArticles
WebMethod:
<script type="text/javascript">
$(".tag_button").on('click', function (e) {
e.preventDefault(); // prevent default action - hash doesn't appear in url
$(this).parent().find('div').toggleClass('tags-active');
$(this).parent().toggleClass('child');
});
</script>
my aspx page (client side):
<div class="tags_list">
<a class="tag-icon tag_button" href="#" >Tags</a>
<div class="tags">
<a class="tag-icon" href="#" >Tag1</a>
<a class="tag-icon" href="#">Tag2</a>
<a class="tag-icon" href="#">Tag3</a>
<a class="tag-icon" href="#">Tag4</a>
<a class="tag-icon" href="#">Tag5</a>
<a class="tag-icon" href="#">Tag6</a>
<a class="tag-icon" href="#">Tag7</a>
</div>
</div>
Change to the following and the eventhandler is attached to dynamically added elements too.
$(document).on('click', '.tag_button', function() {...});
Syntax explanation
Just to clarify the code. The syntax is as follows:
$(document).on(events, cssSelector, handler);
See the full API on jQuery API documentation. By selecting document
we make sure this event handler is loaded to all elements in the document now and in the future.