jQuery not working after loading additional content - javascript

I am quite new to javascript, but I am using it at my website. Last week I found a script that loads additional content to my page via jQuery. Everything was all right until I noticed that my other scripts stopped working because of that. For example I have a script that binds checkboxes:
<script>
$(document).ready(
function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
}
);
</script>
It is inline code. I have read that it could be caused by function ready(), which fires only when the DOM is loaded, but I am not sure how to solve this problem.

Dynamic elements loaded with ajax needs delegated event handlers :
$(document).ready(function() {
$(document).on('change', '.class_of_checkbox', function() {
if (this.checked)
$(".class_of other_checkbox").prop('checked', this.checked);
});
});
Replace the second document with the closest non-dynamic parent, use prop() for properties, and use the change event to capture changes in the state of a checkbox.

Use $.ajaxComplete to rebind your actions when the ajax call completes
http://api.jquery.com/ajaxComplete/
$(document).ajaxComplete(function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
});

Related

jQuery bind event not firing on elements loaded via $().load()

I have a DIV that is in an .html file that is loaded into my document via:
$(document).Ready( function() {
$("#contentDiv").load("some.html")
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
}
});
The event will not fire. If I cut the content of some.html and put it in the document, uhm, "physically", the event will fire.
So, I am pretty sure this issue is related to the fact that the html is injected via .load().
It's bothersome, because if you look at the page source, all the HTML is in fact there, including the button.
So, the question is, is there ANY way to make this work? I am using .load() to reduce page complexity and increase readability, and, code-folding notwithstanding, I really do not want to have to pull all this HTML into the document.
EDIT: This code was just typed in off the cuff. It's not a cut-n-past of the actual code, and it is just to demonstrate what the problem is. But, thanks for pointing it out.
EDIT2: Grrrrrrr. });
load() is asynchronus so you need to the job in the callback :
$(document).ready(function() {
$("#contentDiv").load("some.html", function(){
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
});
});
});
Hope it helps :)
one way is by adding to the some.html the script line which will be loaded as the div appears.
You can add this script to some.html(in a script tag):
registerButton();
and then you can define registerButton() in your current document.
other way, if I remember correctly is by using something like the function bind( )
If you want to fire event on element which was not available at the time when DOM was ready then you need to use .on event.
http://api.jquery.com/on/
$("#saveButton").on("click", function() {
alert("Here I am!");
});
jquery load() function is asynchronous. If you want to bind events to the loaded content, you should put the code into the callback function:
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
//you should put here your event handler
});
});
Your issue is that jquery load() function is asynchronous as #lucas mention. But his code has syntax errors, try this:
$(document).ready(function () {
$("#contentDiv").load("some.html", function () {
$("#saveButton").click(function () {
alert("Here I am!");
});
});
});
Hope it helps now
You need to bind the event handler either after the load OR to the container of the HTML from the load
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
$("#saveButton").on('click',function() {
alert("Here I am! Bound in callback");
});
});
});
OR use: (not needed that it be in the document ready just that the contentDiv be present)
$("#contentDiv").on('click','#saveButton',function(){
alert("Here I am! bound to container div");
});
EDIT: load on the SAVE button click (per comments) (this makes no sense though)
$(document).ready(function() {
$("#saveButton").on('click',function() {
$("#contentDiv").load("some.html", function() {
alert("Here I am! Bound in callback");
});
});
});

Novice issue of this jQuery code not working

I'm really new to jQuery, and I want this code to show an alert box when the button is pressed.
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("button").click(function() {
alert("You clicked.");
});
</script>
<button>Button</button>
I try it, and nothing happens when I click the button.
In jQuery when event handlers are added, you need to make sure that the element is already loaded to the dom else jQuery selector will not return the element so the event handler will not get registered.
The solution is to use the dom ready event handler which will get triggered once the initial dom loading is completed meaning all the elements in the pages is loaded into the dom, it is the safest place to add the event handlers.
jQuery(function($){
$("button").click(function() {
alert("You clicked.");
});
})
As #zzzzBov noted below, it is a short cut for using the lengthy document ready handler
jQuery(document).ready(function($){
$("button").click(function() {
alert("You clicked.");
});
})
Right now, when your code executes, the button has not been loaded so it does not attach the click handler to anything, therefore you need to wrap your jQuery code in $(document).ready(function() { ... }); so that there is for sure a DOM element to attach your handler to, so your code becomes:
$(document).ready(function() {
$("button").click(function() {
alert("You clicked.");
});
});
See the documentation on $(document).ready().
Put your code in ready event
$(document).ready(function(){
$("button").click(function() {
alert("You clicked.");
});
});
You're calling jQuery to add the click handler before you're <button> is declared, so jQuery doesn't find it. Either move the <button> to the top of your snippet, or use a DOM ready function to delay your script execution until the DOM is ready to be manipulated.
Like this:
$(document).ready(function() {
$("button").click(function() {
alert("You clicked.");
});
});
You're running that script before the button exists, put it after instead:
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<button>Button</button>
<script>
$("button").click(function() {
alert("You clicked.");
});
</script>

jQuery Script in External .js file not firing

I have a small piece of script in an external .js file that will not run. Here is the script:
$(document).ready(function () {
$('#chkAllTracts').change(function () {
alert("fired");
})
});
I have a number of other functions in the same .js file that use some jQuery and they all work fine but this is the first jQuery I have attempted to use inside this syntax:
$(document).ready(function (){ }
All I am trying to do is make an alert open when a checkbox is changed (checked or unchecked). The checkbox element "chkAllTracts" is added dynamically using jQuery before this function is called.
$('#checkbox1').mousedown(function() {
if (!$(this).is(':checked')) {
alert("test")
}
});
something like that? (edited)
This worked for me:
$(document).ready(function(){
$("body").append(
$("<input>")
.attr("type", "checkbox")
.change(function(){ alert("It works!"); }))
});
When the document is ready it includes in the body the checkbox input with the change event set to fire the alert message.
It is because your element is dynamically added to the DOM. jQuery selectors would not get hold of it when jQuery first initialise. What you need to do is
$('body').find('#chkAllTracts').change(function () {
alert("fired");
});
I think that should solve your problem.

PopUp is not opening on mousehover

I am not sure what i am doing wrong here.i have a div and i want to open up a popup if user hover over that div section and want to close on mouseout. here is my code
<div class="topCart">
some data
</div>
this is my JQuery code
$(".topCart").mouseover(function() {
$.get('${rolloverPopupUrl}?bustcache=' + new Date().getTime(),
function(result) {
$('#viewCart').html(result);
refreshMiniCart();
});
$('#viewCart').slideDown('slow');
}).mouseout(function() {
$('#viewCart').slideUp('fast');
});
above code is not working nor its giving any Ajax call to fetch fresh data, while if i use following code
$(document).ready(function(){
$(".topCart").hover( function () {
$('#viewCart').html("");
$.get('${rolloverPopupUrl}?bustcache='+new Date().getTime(), function(result){
$('#viewCart').html(result);
refreshMiniCart();
});
if($('#viewCart').is(':hidden')){
$('#viewCart').slideDown('slow'); }
},
function () {
$('#viewCart').slideUp('fast');
});
});
this piece of code is working and its fetching data so i do not see use of document.ready
with my limited knowledge of Jquery i tried but not able to see the reason of not working of code
can any one point me my error?
Try having some basic structure and cleanliness (which is next to godliness) when typing your code, and spotting errors will be much easier:
$(function() {
$(".topCart").on({
mouseenter: function() {
var elem = $('#viewCart');
elem.empty();
$.get('${rolloverPopupUrl}?bustcache=' + new Date().getTime(), function(result) {
elem.html(result);
refreshMiniCart();
});
if (!elem.is(':visible')) elem.slideDown('slow');
},
mouseleave: function() {
$('#viewCart').slideUp('fast');
}
});
});​
The first code does not work becuse not all DOM elements are downloaded when you set events. And it cause that result of $(".topCart") is empty. This not fire any erros, syntax is correct, problem is jQuery works with html, that are not completed.
$(document).ready(...)
or
$(function() {
// Handler for .ready() called.
});
$(document).ready(function() {
$(".topCart").mouseover(function() {
...
}
});
You need to use the document.ready before events can fire, after the document all DOM elements have loaded which you can be sure of, otherwise you're looking for an event which hasnt laoded into the DOM
Without the $(document).ready(), the first has not actually been bound to $('.topCart').
The second example, using the document ready gives a moment or time at which to bind the function to the hover event.

Trigger a jQuery Event Handler Assigned in a Different Code Block

I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block. How can I accomplish this?
The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.
Example HTML:
<p id="Element1">Element One</p>
<p id="Element2">Element Two</p>
First jQuery code block:
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
Second jQuery code block:
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').click();
});
});
UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using. Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.
You need to trigger a click when you click on the first element. You can use the trigger method for this.
function element1Hanlder () {
alert('Element One');
}
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').trigger('click');
});
});
EDIT: This is based on JohnP's "trigger" suggestion (so you should choose him as the right answer)...
If I load this block from an external js file...
$(document).ready(function() {
$('#Element1').click(function () {
alert( $(this).text() );
});
});
Then load this in a script tag within the HTML itself...
$(document).ready(function() {
$('#Element2').click(function () {
$('#Element1').trigger('click');
});
});
Seems to be working as intended.

Categories