toggleClass not working when coming from an AJAX request - javascript

I have a webpage with a link to make an AJAX request. When the following .js comes back the toggleClass function does not work.
$(document).ready(function(){
$("td").click(function(){
$(this).toggleClass("br");
});
});
If I replace toggleClass("br") with something like addClass("br") then that does work.
Furthermore, toggleClass works fine if I put the .js into the html page or if I run it from the console. It seems that something about both toggleClass and AJAX requests together stops this code from working but I have no Earthly idea as to why that might be.
UPDATE
I've figured out the problem. I had accidentally included jQuery two times and so javascript from AJAX requests was being run twice. Hence why only toggleClass was "not working" while addClass and removeClass were.
The only mystery left is why this was only the case when the .js came from an AJAX request as opposed to when it was in the HTML itself.

Assuming you want the click handler to be on an element that is populated by the AJAX query, you have to late bind the event to a DOM element that exists before the AJAX query fires. Let's say you have the following HTML:
<html>
<body>
<table id="populatedByAjax"></table>
</body>
</html>
...and you know you're going to populate the table via AJAX. Then we need to declare our jQuery selector like this:
$("#populatedByAjax").on("click", "td", function(){
$(this).toggleClass("br");
});
That makes sure that the click event is bound to any current or future td elements in the selector #populatedByAjax

Use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
$(document).on('click', '#td', function() {
$(this).toggleClass("br");
});

Related

Re-bind a jquery on click after I have ajaxed the page

So I have three images that when you click on them brings up a larger image. A really basic gallery I made. Any way when im changing content on the page with the .load(), it doesnt register the click any more for the div.
How to I reload the jquery or reload the event handlers?
Here is what I was trying
function recheckTheImageClickers(){
$('#img1').on('click', function(){
change1();
});
});
I tried to run this function after the ajax to see if it would re-bing the $img1 to a click function but no luck.
Any ideas?
I worked it out, I wasn't running the function in the success part of .load(). It works now.
This looks like a perfect spot for jQuery's live or delegate (both now deprecated in favor of using on with more parameters):
$(parentSelector).on('click', '#img1', function(){ change1(); });
As long as your parentSelector is outside of the AJAX refreshed DOM elements, and #img1 is a child of said parent, this should work without needing to re-execute it.

call on .load in not working properly

I have a page xyz.jsp which having a script on page load and its working fine.
function loginRegOverlay() {
$("#hiddenLoginButton").click();
};
but if i am calling this page on abc.jsp on jquery .load page is rendering but
$("#hiddenLoginButton").click(); is not working.
dont know the reason why its not coming.
please tell me that its working onload of xyz.jsp but if i calling that page on abc.jsp it not working
Adding code which is in abc.jsp:
function newstyle(){
$("#test").load("xyz.jsp");
};
so, newstyle calling onload on abc.HTML rendering fine but
function loginRegOverlay() {
$("#hiddenLoginButton").click();
};
which is in xyz.jsp not working fine if i am calling that on abc.jsp..i hope its clear now.
.load() is an ajax request so if you are loading elements from other page then direct binding of events to the element won't work. So workaround to this is event delegation which you have to delegate the event to the existing parent item which is loading the html from other page.
$(document).find('#hiddenLoginButton').click();
You can delegate it to the closest parent which was available at the time of page load:
$('#ID or .Class of the parent item').find('#hiddenLoginButton').click();
like:
$('#wrapper').find('#hiddenLoginButton').click();
side note:
if you are able to post some rendered html then that would be much better to see what is going on and what will be suggested to overcome this.
Try with .trigger like
$("#hiddenLoginButton").trigger('click');
and we assumed that you have called the function loginRegOverlay() on page load
AND I have noticed that you wrote code in xyz.jsp and you want to trigger it on abc.jsp then include that xyz.jsp at abc.jsp
inlcude('xyz.jsp');
and plz makesure that those buttons ids are unique bec xyz is loads on abc and due to duplicate in ids they wont work,you can give them same class and fire it as once
You can use .live or .on method for event delegation
$("#hiddenLoginButton").live('click', function(){});

Ajax loads new button, do I need to load a new selector?

Let's say that I'm coding a message system for example. Users can add messages (via AJAX) and next to their messages they've got some buttons. (Edit, Remove, ...)
By loading the page, a few messages are loaded.
<div class="message">
<p>blaat</p>
Remove
</div>
<div class="message">
<p>blaat</p>
Remove
</div>
The jQuery selector knows these elements. Because they already exist when I execute the jQuery script. (document.ready)
But when I add another "message", jQuery can't handle the 'remove' link because it's loaded after running the jQuery script.
Can somebody help me out? Thanks in advance!
You can use the live method instead of bind (or the shorthand click). So it'd look like:
$('.btnRemove').live('click', function(e) { ... });
This uses event delegation, with the click event handler attached to document rather than any particular element.
You can use jQuery Live method to work on remove which is loaded using ajax.
can you post the JavaScript code with this example? off the top of my head I know the $().live function in jQuery would probably be a good fit for your needs as it will handle the buttons when they are added to the DOM... For example:
$('.btnRemove').live('click', function(e) { ... });

jQuery document.ready fired but elements aren't found

I have a problem that happens only on a specific computer(FFX 3.6.13,Windows 7,jQuery 1.4.3).
Sometimes document.ready is fired but when trying to get elements to attach the event handlers,the elements don't exist!
the code goes something like this:
$(function(){
window.initStart = true;
$("#id_of_element").click(function()...);
window.initEnd = $("#id_of_element");
});
the window.initStart/End are there for debugging,sometimes this code runs just fine,but sometimes window.initEnd is just a empty jQuery set(length == 0).
What this means is that document.ready is always fired,but sometimes it is fired before elements are available.
Does anybody had this problem? what could the problem be?
One way that you could try to get around this would be with using .live instead of .click. The following code
$('#idOfDiv').live('click', function() { doStuff(); });
will attach the input function to the click event of everything that is dropped on the page with an id of 'idOfDiv' as soon as it makes it to the page. Whereas .click executes immediately, this should be attached no matter what time the divs make it to the page.
Cheers
There's an article on SitePoint that demonstrates how to sense when certain dom elements are available.
Also I know this is a version specific issue, but if you were on Jquery 1.5 the deferred objects stuff would be useful here.

jquery ajax events called on every element in the page when only targeted at one element

So, you have a page:
<html><head>
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
$(function() {
var onajax = function(e) { alert($(e.target).text()); };
var onclick = function(e) { $(e.target).load('foobar'); };
$('#a,#b').ajaxStart(onajax).click(onclick);
});
</script></head><body>
<div id="a">foo</div>
<div id="b">bar</div>
</body></html>
Would you expect one alert or two when you clicked on 'foo'? I would expect just one, but i get two. Why does one event have multiple targets? This sure seems to violate the principle of least surprise. Am i missing something? Is there a way to distinguish, via the event object which div the load() call was made upon? That would sure be helpful...
EDIT: to clarify, the click stuff is just for the demo. having a non-generic ajaxStart handler is my goal. i want div#a to do one thing when it is the subject of an ajax event and div#b to do something different. so, fundamentally, i want to be able to tell which div the load() was called upon when i catch an ajax event. i'm beginning to think it's not possible. perhaps i should take this up with jquery-dev...
Ok, i went ahead and looked at the jQuery ajax and event code. jQuery only ever triggers ajax events globally (without a target element):
jQuery.event.trigger("ajaxStart");
No other information goes along. :(
So, when the trigger method gets such call, it looks through jQuery.cache and finds all elements that have a handler bound for that event type and jQuery.event.trigger again, but this time with that element as the target.
So, it's exactly as it appears in the demo. When one actual ajax event occurs, jQuery triggers a non-bubbling event for every element to which a handler for that event is bound.
So, i suppose i have to lobby them to send more info along with that "ajaxStart" trigger when a load() call happens.
Update: Ariel committed support for this recently. It should be in jQuery 1.4 (or whatever they decide to call the next version).
when you set ajaxStart, it's going to go off for both divs. so when you set each div to react to the ajaxStart event, every time ajax starts, they will both go off...
you should do something separate for each click handler and something generic for your ajaxStart event...
Because you have a selector with two elements, you're creating two ajaxStart handlers. ajaxStart is a global event, so as soon as you fire any ajax event, the onajax function is going to be called twice. So yes, you'd get two popups.

Categories

Resources