I have the following html code:
<div>
<span>Products per page:</span>
<a class="selectview" href="/womens-clothing/shorts?page=1&view=20">20</a>
<a class="selectview" href="/womens-clothing/shorts?page=1&view=200">200</a>
<div>
and the jQuery is as follows:
jQuery('.selectview').click(function (ev) {
ev.preventDefault();
var alink = jQuery(this).attr('href');
var view = getLinkVars(alink)["view"];
var page = jQuery("#currentpageno").val();
alert(alink);
alert(view);
alert(page);
run_ajax(view,page);
});
The code runs fine the first time if I click on any of the links; I see the alerts and the ajax code runs fine, but when I click on it the second time, the whole page is refreshed and no alerts are shown. Then if I click on it again it works, then when I click on it again it works, and so on.
What could I be doing wrong?
My guess is that run_ajax
is replacing the links with new ones. .click
only binds to the elements that matched the selector at that time. The newly added links won't have a click event bound to them.
You need to make the events "live". Bind them using .on
like so:
jQuery(document).on('click', '.selectview', function (ev) {
ev.preventDefault();
// code...
});
This will "delegate" the event. It will run for all .selectview
links no matter when they are added to the DOM.
.live('click', function(ev) {})
rather than the slightly less popular .on
syntax. Essentially having to do dynamic binding to the click event rather than static binding will work here - Mattygabe 2012-04-04 18:17
.live
was commonly used before jQuery 1.7. In jQuery 1.7+, .live
, as well as .bind
and .delegate
are deprecated. jQuery suggests you use .on
for all your event binding needs. .on
should be more "popular" once people upgrade their code - Rocket Hazmat 2012-04-04 18:19
If run_ajax is replacing the links you can wrap the code that attaches your click handlers, and then inside run_ajax you can call the wrapper after you've replaced the links with the new content:
var setupClickHandlers = function(container) {
jQuery(container).find('.selectview').click(function (ev) {
ev.preventDefault();
var alink = jQuery(this).attr('href');
var view = getLinkVars(alink)["view"];
var page = jQuery("#currentpageno").val();
alert(alink);
alert(view);
alert(page);
run_ajax(view,page);
});
};
setupClickHandlers(container);
The in run_ajax:
var run_ajax = function(view, page) {
// do your stuff here
// set up click handlers on the new content
setupClickHandlers(container);
}