Reputation: 43
I have this code which works great if <a> is placed outside the <div id="list"> but not when the link is placed within the target div. The event.preventDefault() is not even triggered. Any help would be highly appreciated. Thanks!
<script>
$( document ).ready(function() {
$( ".category_link" ).on('click' ,function () {
event.preventDefault();
var addressValue = $(this).attr("href");
function getUrlVars()
{
var vars = [], hash;
var hashes = addressValue.slice(addressValue.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
site_location = getUrlVars()["location"];
category_id = getUrlVars()["category_id"];
per_page = getUrlVars()["per_page"];
request_type = getUrlVars()["request_type"];
//send the request via ajax
$.ajax({
type: "POST",
url: "/test/testing/",
data: {site_location : site_location, category_id : category_id, per_page : per_page},
dataType: "html"
}).done(function( msg ) {
//get the returned message
$( "#list" ).html(msg);
});
});
});
</script>
<div id="list">
<a class="category_link" href="/?site_location=testing&per_page=testing&category_id=testing&request_type=testing">Test</a>
Upvotes: 0
Views: 284
Reputation: 15112
$( ".category_link" ).on('click' ,function ()
This event is not triggered if category_link
is dynamically added to the #list
container. You have to handle event delegation as shown below.
replace your above event with
$("#list").on('click', '.category_link', function (event)
Note: event.preventDefault()
will work if you pass it in your function as above
Upvotes: 1
Reputation: 27022
You bind your click handler to that a
element. When the ajax finishes, it replaces the a
element with a new one, which doesn't have a click handler bound to it.
Use this instead:
$("#list").on('click', '.category_link', function (event) {
That version of on()
uses event delegation, and works with dynamic elements.
See on()
, especially the part about direct and delegated events.
(Note that you should add the event
parameter. Some browsers don't care, others do.)
Upvotes: 2