Ajax Call Is Breaking Jquery Toggle Function
Solution 1:
If the portion of the page containing the element that's clicked is replaced by the AJAX results, then the handler will be lost. You could do something like this instead:
$(function() {
var toggleState = 0;
$('body').delegate('th#seeking', 'click', function() {
if (toggleState === 0) {
$("a.add_listing").hide(200);
$("a.add_listing").show(200);
}
else {
$.ajax({
type: "POST",
url: "ajax_calls.php",
data: "order=instrument_asc&sort_item=true",
success: function(r){$("#listings").html(r);},
error: function(){
alert(2);
$("#error").text("Could not retrieve posts")
.fadeIn(300).delay(900).fadeOut(300)
}
});
}
toggleState = toggleState ^ 1;
});
});
That sets up a "click" handler and keeps track of the toggle state explicitly, but it makes the handler work on the event as it bubbles up to the <body>
(you could put the handler at a closer container in the DOM if you wanted to). Thus even if you replace the page fragment, as long as the new fragment has that "id" value on the table header, the delegated event handler will "see" it.
edit — I changed that slightly to indicate that this should be done in a "ready" handler, or in some other way such that the <body>
element exists in the DOM. If the code were to run in a <script>
block in the <head>
without being set up as a "ready" or "load" handler, then the <body>
won't be there and it won't do anything.
edit again — Here is a faked-up demo. There was a big in my code above (missing "})" towards the end) that I've fixed in that fiddle, and that I'll fix here too.
Solution 2:
I would have thought using jquery.live() would be a good solution, like the answer seen here: Using jQuery .live with toggle event
Post a Comment for "Ajax Call Is Breaking Jquery Toggle Function"