This question comes from
Actually, I was able to find a clue and this is what I found. I have a js file:
$(document).ready(function() {
var myIdElement = $("#some_id");
//............
$.ajax({
url: getFullUrl(myIdElement.val())
})
//..........
So when I come to this page from the another page by a link (html link) then myIdElement is undefined. However, when I reload the page it starts having a proper value. I use turbolinks.
How do I get it to work in all situations?
$(document).ready does not always fire in turbolink. Use page:load event, instead. On the first page, it fires ready event, but on subsequent pages, document has always been ready, hence no document ready event is fired. So, it fires page:load to help us.
function ready () {
// Your code goes here...
}
jQuery(document).ready(ready);
jQuery(document).on('page:load', ready);
Try this:
(function($) {
$(document).ready(function() {
var myIdElement = $("#some_id");
//............
$.ajax({
url: getFullUrl(myIdElement.val())
})
//..........
})(jQuery);
Related
I'm using ajax but is there any option to call function after ajax content fully loaded like $(window).load() or window.onload? When i'm in fresh page everything working fine with $(window).load() or window.onload function because some scripts work after window complete load. But the problem is in ajax and when i click on a link and page is dynamically load contents from another page so we don't need $(window).load() or window.onload function but because some script only work when window loaded or content fully loaded so how to call function after ajax content fully loaded like $(window).load() or window.onload ?
function windowload() {
//Some functions works only after window load
};
$(function() {
$(window).on('load', windowload);
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var $this = this.href;
$.ajax({
url: '' + $this + '',
dataType: 'html',
success: function(html) {
var div = $('#style', $(html));
$('#style').html(div);
//call windowload but not working
windowload();
//Also tried this but not working
$('#style').on('load', function(){
windowload();
//Some functions work only after ajax content fully loaded
});
});
});
Edit :
I need a function after ajax content fully loaded not after ajax request complete.
I have been trying to find the solution to this exact same problem for hours. What worked for me was
$(document).ajaxComplete()
I put my code in there and when Ajax was complete and the content of the div fully reloaded, I added the style I wanted to add. Hope this helps someone. Calling the method from ajax success won't work.
If you need to call a single function at multiple points in the pages lifecycle (as you describe above, where the logic is needed on both page load and also when an AJAX request completes), then you can extract the required logic to its own function to be called as needed. Try this:
function htmlLoaded() {
// Some functions work only after window load
}
$(window).load(htmlLoaded); // called on page load
$(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
$.ajax({
url: this.href,
dataType: 'html',
success: function(html) {
var styleHtml = $(html).find('#style');
$('#style').html(styleHtml);
htmlLoaded(); // called after the AJAX request completes successfully
});
});
});
});
Also note that I made a couple of amendments to improve the logic in your JS code.
Try this:
$("#Style").ready(function(){
console.log('Style is fully loaded.');
windowload();
});
Hope this will help.
When you call a function you must use the () symbol like windowload().
Here is the fixed, well-indented code : (I removed the empty quotes, useless here)
function windowload() {
//Some functions works only after window load
};
$(function() {
$(window).on('load', windowload);
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var $this = this.href;
$.ajax({
url: $this, // Removed the empty quotes which are useless here
dataType: 'html',
success: function(html) {
var div = $('#style', $(html));
$('#style').html(div.html());
$('#style').ready(windowload);
}
});
});
});
By adding a new script tag which will run the windowload() function, we solve the problem. Because when this script is runned all HTML content placed before this tag has been loaded.
I am a newbie on javascript and was implementing a loader in the project..
I have used the below code for the implementation of loader but it is not working:-
var url = "http://localhost:3500/#!/Movies";
<script>
$(function(){ //Loader implementation
if (location.href==url){
$(window).ready(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
});
}
});
</script>
I am calling the loadindicator in the code as:-
<ul>
<li id="loadIndicator1" style="position:absolute ;top:50%;left:50%;z-index:99999;"></li>
</ul>
I am not very sure why this is giving an issue.I am using jquery-1.8.3.min.js and jqueryui-1.10.2.js
Also when I hover on location..I get unresolved variable location.Please help me with this.
use
if (window.location.href==url)
instead of
if (location.href==url)
var url = "http://localhost:3500/#!/Movies";
$(function(){
if (location.href==url){
$(window).load(function(){
$('#loadIndicator1').fadeIn(1000);
});
}
});
this will show your loader once the webpage is fully downloaded
use $('#loadIndicator1').fadeOut(1000); to hide the loader once the content is loaded.
Ignoring window ready, using only document ready
$(function() {
if (window.location.href === url){
// $(window).ready(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
// });
}
});
You should remove the part I have commented out. The problem is, you attached an event handler to document ready, and if your are on a specific URL, you attach an event handler to window ready, but that event was already fired, and it won't be fired again.
Using window load after document ready
Another possible solution:
$(function() {
if (window.location.href === url){
$(window).load(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
});
}
});
The window load event fires later, than document ready - though this should be tested.
Ignoring document ready, using only window load
Third time is a charm, another solution which may be the best, simply ignore the document ready event, and only use the window load:
$(window).load(function () {
if (window.location.href === url) {
$('#loadIndicator1').fadeOut(1000);
return false;
}
});
This case though the loader only appears if everything is loaded on the page, so maybe this is not what you want -- in this case use the first option.
Strange situation:
I am building a menu bar using jQuery and CSS.
In my JavaScript file, I have an on-ready function like so:
$(document).ready(function(e) {
mark_active_menu();
}
and...
function mark_active_menu() {
var elementWidth = $("nav li").width();
alert(elementWidth);
}
For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.
Why my function is being called BEFORE all the document finish loading?
Is there a way to load the function only AFTER a certain element done loading (Example: the nav element)?
You can use window.load, it will be triggered after all the resource have completed loading.
$(window).load(function(e) {
mark_active_menu();
});
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading, Reference
All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.
var ajax1 = $.ajax();
var ajax2 = $.ajax();
jQuery(function($) {
$.when.apply($, [ajax1, ajax2]).done(function() {
// your code here
});
});
Try on the window load event :
$(window).load(function() {
//Stuff here
});
To be sure, Try window load
$(window).load(function(e) {
mark_active_menu();
}
Before(sometimes, doesn't load absolutely at the beginning, a few milliseconds after(0-200ms about)):
$(document).ready(function(){
$('body').hide(0);
});
After:
$(window).load(function(){
$('body').delay(500).show(0);
});
In my situation of work with AJAX and HTML. I have the same problem with functions $(document).ready() and $(window).load(). I solved this problem by adding handler of my event (that should work at HTML DOC), to the jQuery function that runs right after AJAX reguest was finished. Read this: "
jQuery.post()" (third parameter in the function).
In my code it looks like this:
var RequestRootFolderContent = function(){
$.post(
'PHP/IncludeFiles/FolderContent.inc.php',
function(data){
$('[class~="folder-content"]').html(data);
//Here what you need
$('[class~="file"]').dblclick(function(){
alert("Double click");
});
}
)
}
I have following small jQuery script:
$("#content").on("keyup", "#ID1", function() {
$("#ID2").load("loadText", resizeResult());
});
function resizeResult() {
if($("#ID2").height() != $("#ID3").height()){
$("#ID3").animate({
height: $("#ID2").height()
}, 800);
}
}
My problem now is that the resize function will be only executed by the NEXT "keyup" event but I want it immediately when the "load" in ID2 is done.
Call resizeResult() in the end of keyupfunction
$("#content").on("keyup", "#ID1", function() {
..................
resizeResult();
});
call your load function in document.ready too..
$(function(){
$("#ID2").load("loadText", resizeResult()); //<-- call load function in document ready and in keyup function..
$("#content").on("keyup", "#ID1", function() {
$("#ID2").load("loadText", resizeResult());
})
.....
});
and please make sure your url in load is proper path... loadText doesnot seems to be a proper path
Everything looks well in your code. But you need to leave the brackets from the resizeResult function inside the event. Because you don´t want it to call immediately when the browser executes the script. It´s only needed when the event is fired. So you should change your code to this (and my also native common events, which recommend jQuery):
$("#content").keyup(function() {
$("#ID2").load("loadText", resizeResult);
});
function resizeResult() {
if($("#ID2").height() != $("#ID3").height()){
$("#ID3").animate({
height: $("#ID2").height()
}, 800);
}
}
For a safe execution it´s also better to wait until the html is fully loaded or until this html tags are loaded (javascript code after the ID3 container). The first method can be done by using $.document.ready from jQuery.
After the request, the new elements created are not recognized by the event handlers in my jQuery code.
Is there a way to reload the file to re-register these events?
I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?
Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.
e.g.
replace
$('div.someClass').click(function(e){
//do stuff
});
with
$('div.someClass').live('click', function(e){
//do stuff
});
Important:
While I've recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in #jbabey's comment for important information.
This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div> bloc and want to catch the onClick event.
//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
//do stuff
});
// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
//do stuff
});
// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
//do stuff
});
You would find the documentation here: http://api.jquery.com/on/
This codes works perfect for me..
$("head script").each(function(){
var oldScript = this.getAttribute("src");
$(this).remove();
var newScript;
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = oldScript;
document.getElementsByTagName("head")[0].appendChild(newScript);
});
It removes the old script tag and make a new one with the same src (reloading it).
To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.
For example,
$("#load").click(function(){
$.getScript('helloworld.js', function() {
$("#content").html('Javascript is loaded successful!');
});
});
when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.
Try it yourself
In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<h1>Load Javascript dynamically with jQuery</h1>
<div id="content"></div>
<br/>
<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>
<script type="text/javascript">
$("#load").click(function(){
$.getScript('js-example/helloworld.js', function() {
$("#content").html('
Javascript is loaded successful! sayHello() function is loaded!
');
});
});
$("#sayHello").click(function(){
sayHello();
});
</script>
</body>
</html>
In your request callback, call a function that acts on your newly appended or created blocks.
$.ajax({
success: function(data) {
$('body').append(data);
//do your javascript here to act on new blocks
}
});
simple way to solve this problem
$(document).ready(function(){
$('body').on('click','.someClass',function(){
//do your javascript here..
});
});
You can also attach the click handlers to the body so that they never get destroyed in the first place.
$('body').on('click', 'a', function(event) {
event.preventDefault();
event.stopPropagation();
// some stuff
})
var scripts = document.getElementsByTagName("script");
for (var i=0;i<scripts.length;i++) {
if (scripts[i].src)
if(scripts[i].src.indexOf('nameofyourfile') > -1 )
var yourfile = scripts[i].src;
}
jQuery.get(yourfile, function(data){
if(data){
try {
eval(data);
} catch (e) {
alert(e.message);
}
}
});
You can try loadscript plugin for loading the javascript file.
forexample
$("#load").click(function(){
$.loadScript('path/example.js');
});
or
$.ajax({
success: function(data) {
$.loadScript('path/example.js');
}
});
http://marcbuils.github.io/jquery.loadscript/
What do you mean not recognized by jQuery?
jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.
What isn't visible exactly?
P.S.: Reloading JavaScript is possible, but highly discouraged!