There is one div which changes frequently it's innerHTML by ajax. Once the page loads, jQuery function() works but when innerHTML changes by ajax then some functionality doesn't work. I checked the code using firebug and try to explain it in short.**
I think DOM loads the js file only when the page loaded first time and if ajax modifies innerHTML then function is not invoked somehow.What you say? what could be solution according to you?
HTML page
<body>
<div class="_div_change"> dynamically class add by jQuery function()
here contenet is added by ajax functionality
</div>
<script type="text/javascript">
$(function(){
$('._div_change').addClass('.div_class');
});
</script>
</body>
Loading first time & class is added by fn() |only div innerHTML modified by ajax ***
|
<div class="_div_change div_class"> | <div class="_div_change">
innerHTML elements added successfully| innerHTML elements altered successfully
</div> | </div>
Your script is incomplete, but assuming that it looks like this:
$(function(){
$('._div_change').addClass('.div_class');
});
...then what you're doing there is telling jQuery to run that function once when the DOM is initially loaded (calling $() with a function is a shortcut to jQuery.ready). If you want to re-run that function when you update the div's contents via ajax, you'll have to do that in your success handler on the ajax call.
You can give jQuery a function that it will call whenever any ajax call is complete, via jQuery.ajaxSuccess, which may be useful.
Yes, the code only runs once when the page loads.
The $(function(){...}); is the short form of hooking up the ready event for the document: $(document).ready(function(){...});.
If you change the DOM and want to apply the jQuery code to the new elements, you should rerun the code with the parent element as scope. Create a function with the code and a scope parameter:
function updateElements(scope) {
$('._div_change', scope).addClass('.div_class');
}
Now you can run the function from the ready event with the document as scope:
$(function(){
updateElements(document);
});
When you have loaded new content into an elements, lets say one with id="asdf", you can rerun the function with that element as scope, and it will apply the changes only to the newly added content:
updateElements($('#asdf'));
Related
I have Jquery function that executes AJAX query to server.
How can I call this after load page in the specified url page? May I bind this to element HTML, I mean:
<div id="graph" onload="function()"></div>
jQuery handles the HTML file with a variable called document.
Document has two popular event states
load when the page has been loaded
ready when the page has been loaded and all other decorations to the HTML have been applied.
jQuery provides hooks for these states.
To run javascript code after each of the events listed above, you have to put the function within the appropriate event scope.
For loading, this would be…
$(document).load(function() {
// javascript code you want to execute
})
After the page has been ready, but not yet rendered, you can apply some other javascript code using
$(document).ready(function() {
// javascript code you want to execute
})
One way using jQuery:
$(document).ready( function() {
//do whatever you need, you can check if some element exists and then, call your function
if($("#graph").length > 0)
callfunction();
});
No jQuery, only vanilla js:
window.onload = function() {
if(document.getElementById("graph"))
callfunction();
}
Does $(document).ready(function() { means all javascript file has been downloaded so any js init or func should work?
so it is a good practise to always put js inside $(document).ready(function() { ?
$(document).ready is part of the page lifecycle and runs after all of the resources have been loaded for the page (HTML, CSS and JS files).
You should be functions in here that you need to run when the page first loads, so generally initialization of plugins, first run functions and attaching events to elements.
Any other functions that can run after the page has loaded can be defined outside of this scope.
Note that if you are dynamically inserting DOM elements, any events attached to that type or class (for example) will not be attached to them without re-attaching, or using .on and attaching to the document itself.
Use ready() to make a function available after the document is loaded:
for eg:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
Definition and Usage
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions. Like in the example above.
The ready() method specifies what happens when a ready event occurs.
note: The ready() method should not be used together with <body onload="">.
From jQuery documentation:
Description: Specify a function to execute when the DOM is fully loaded.
It means that you can specify a function to run after the DOM is fully loaded, ie is available to interact with javascript.
Following is copied from here
$(document).ready(...)
Fire when all DOM loaded (even if multimedia no loaded yet)
$(window).load(...)
Fire when all content loaded (progress indicator which shows loading proccess) gone.
Now here is my suggestion (not from that link)
I think the better approach would be putting your script tags at the end of body, like this, as it makes sure that the script is loaded when everything else has been loaded
<html>
<head></head>
<body>
<div>
bla bla bla
</div>
<script src="1"></script>
.
.
<script src="n"></script>
<script>console.log('hello');</script>
</body>
</html>
I'm just messing with some javascript and I came across something that puzzled me a little.
I've added a link to a script file into the header of a document, just after the link to jQuery.
If I place in the test file:
(function($){
$("#thing").mouseover(function(){alert("woo");});
})(jQuery);
The mouseover event does not trigger the function.
However, if I add
(function($){
$(document).ready(function(){
$("#thing").mouseover(function(){alert("woo");});
});
})(jQuery);
The event does work.
Is it simply that without $(document).ready the DOM hasn't finished loading at the point when my self-executing function runs, so there is no #thing yet to attach the function to or is there another explanation?
I've added a link to a script file into the header of a document
This is the point.
Usually people put script files in the footer of document to optimize the process of loading the page, therefore it would not need to wait for the document to be ready to execute something based on the DOM already loaded (if you are in the footer, you have already loaded the rest - unless you have some content loading async).
Try putting your script file in the footer, and you will not need the $(document).ready.
Summary: In your case you need it, because when the script starts executing you have not started yet looking for the DOM, and the element cannot be found in that time.
It's because document ready waits until the document has fully loaded before executing.
Anything that binds to DOM elements must be done when the document is fully loaded otherwise those event handler bindings will be trying to bind to DOM elements which don't yet exist.
So yes, you answered your own question.
$( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute
It waits for the entire HTML excepts the Images.
some times you noticed that you recived an error “$ is not defined.” then in that case
you can use $( document ).ready()
You can just move the $ to make it work
$(function(){
$("#thing").mouseover(function(){alert("woo");});
});
Demo
Explanation $(function(){}); is equivalent to $(document).ready(function(){}); in jQuery
The document ready function waits for the page to load and
then executes whatever is in there. This prevents immature
actions before the page loads.
As a thumb rule, remember this,
$(document).ready(function(){
//jQuery code goes here
});
Apparently this works for me
<div id="body">
<section class="featured">
<div class="content-wrapper">
...
</div>
</section>
</div>
#section scripts{
<script type="text/javascript">
(function ($) {
$(".featured").mouseover(function () { alert("woo"); });
})(jQuery)();
</script>
}
it is basically a immediately executing function.
I wanted to load some fragments of external content inside a div, through a menu.
Found "load" and "live", found a tutorial used it = success!
Except, like what's explicit in the documentation, it doesn't load JavaScript.
The thing is, the destination page already loads, inside the header, that same JavaScript, 'cause Wordpress loads it in every page. In this particular page, I'm only using the plugin (nextgen gallery) through the jQuery AJAX call.
So, what I believe is my problem is that I somehow need to alert/reload the JavaScript, right?
And how can I do this?
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
// ajax pagination
jQuery('#naveg a').live('click', function(){ // if not using wp-page-numbers, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('#fora').html('<div class="loading"><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('#fora').load(link+' #dentro')
return false;
});
}); // end ready function
</script>
PS: I've substituted "live" with "on" but didn't work either.
I'm not sure if I understand... your load() command is puling in some Javascript that you want executed? I'm not sure if you can do that. But if you just need to call some JS upon load() completion, you can pass it a function like so:
jQuery('#fora').load(link+' #dentro', function() {
console.log("load completed");
// JS code to be executed...
});
If you want to execute Javascript code included in the loaded page (the page you retrieve via .load()), than you have to use the url-parameter without the "suffixed selector expression". See jQuery documentation for (.load()):
Note: When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is however called with a selector expression appended to the
URL, the scripts are stripped out prior to the DOM being updated,
which is why they are never executed. An example of both cases can be
seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
However in this case, script blocks in the document being loaded into
#b are stripped out prior to being executed:
$('#b').load('article.html #target');
I think that's your problem (although I have no solution for you, sorry).
Proposal: Maybe you can load the whole page (including the Scripts) and remove (or hide) the parts you don't need?
Cheers.
I'm appending some code to my page using jQuery AJAX calls. This code is a mix of html and javascript. But I want javascript to be executed only when html part is ready. But what event is raised when appended html is rendered?
Here is an example:
<table id="sampleTable">
...
</table>
<script>
// this code should be executed only when sampleTable is rendered
$('#sampleTable').hide();
</script>
Use the jQuery ready() event:
$(document).ready(function() {
$('#sampleTable').hide();
}
<edit> It seems to be impossible to call a ready event on any other object than Document, my bad </edit>
This is an option if you are talking about the event triggered after a successful Ajax request :
$('#sampleTable').ajaxComplete(function() {
$(this).hide();
});
Or just hardcode the style of the table to display:none;...
Wrap your javascript in a "ready" handler. This will fire when the DOM has been updated and is undoubtedly what you want to do.
$(function() {
$('#sampleTable').hide();
});
$(document).ready(function() {
$('#sampleTable').hide();
});
http://api.jquery.com/ready/
You're loading both the <table> and the <script> into the document at once? Don't.
Inserting HTML with <script> elements into the page using html()/load() is highly unreliable. The script doesn't run directly from innerHTML inclusion; different browsers treat such inserted script elements differently. jQuery attempts to fix some of this but doesn't quite get it quite right (it may not be possible to get it quite right).
It's best to keep your static code in static script, so that the caller knows it has to call hide() on the table just after the AJAX call completes and the content is inserted. If you really have to pass back dynamic code to run, keep it separate from the HTML, eg. by returning a JSON object with both HTML and code members.