Reload javascript file after an AJAX request - javascript

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!

Related

make the div load last using jquery or javascript

I am trying to make my div on my page to load last, what i mean is after everything is loaded then it must load that div using jquery or javascript ?
here is what i tried
<script type="text/javascript">
$(document).ready(function(){
$.get('url', function(data) {
$('.image').html(data);
});
});
</script>
Don't use $(document).ready() because this event fires probably too early for your intention. Use the window.onload event which fires after the page is fully loaded (including images and other resources)
window.onload = function() {
$.get('url', function(data) {
$('.image').html(data);
});
};

Rails:-location.Href not working in project

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.

How to load a jQuery function only after the document finish loading

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");
});
}
)
}

What is the proper way to initiate a JavaScript function on load in a CMS?

I need to call a function on page load. Typically this would be handled with a body onload call, however I'm in a CMS that reuses the body tag on multiple pages. I only need the script to run on a single page. Is there a next-best-location to initiate an onload function?
Use the window.onload event:
window.onload = function() {
// do stuff
};
If you have access to jQuery, you can use one of the .ready() syntaxes:
$(document).ready(function() {
// do stuff
});
OR:
$(function() {
// do stuff
});
You can instantiate it in a separate js file, so it will only be called when that file is loaded, not the CMS template. i.e.
window.onload = function(){
// Do stuff
};
If you are using jQuery, you can add a load event on window:
$(window).on('load', function(){
// do stuff here
})
You also have DOM ready with jQuery:
$(function(){
//stuff here
});

Calling Javascript in a page after it's been loaded by jQuery GET

Imagine a normal page calling javscript in head. The trouble is some of the content isnt loaded untill i click on a link. Subsequently when this link loads the content it wont work. This is because i guess the javascript has already been run and therefor doesnt attach itself to those elements called later on. There is only standard html being called.
So for example this is the code which calls my external html.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).slideDown('slow');
});
});
If the html i was calling for example and H1 tag was already in the page the cufon would work. However because i am loading the content via the above method H1 tags will not be changed with my chosen font.This is only an example. The same will apply for any javascript.
I was wonering whether there is a way around this without calling the the javascript as well the html when its received from the above function
If you want to attach events to elements on the page that are dynamically created take a look at the "live" keyword.
$('H1').live("click", function() { alert('it works!'); });
Hope this is what you were looking for.
Does Cufon.refresh() do what you want?
As you said Cufon was just an example, I'd also suggest a more general:
$.get(url, options, function(html, status) {
var dom = $(html);
// call your function to manipulate the new elements and attach
// event handlers etc:
enhance(dom);
// insert DOM into page and animate:
dom.hide();
$target_element.append(dom); // <-- append/prepend/replace whatever.
dom.show(); // <-- replace with custom animation
});
You can attach event handlers to the data that you get via the get() inside of the callback function. For example
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).find('a').click(function(e) {
// specify an event handler for <a> elements in returned data
}).end().slideDown('slow');
});
});
live() may also be an option for you, depending on what events you want to bind to (since live() uses event delegation, not all events are supported).
Andy try this. It will call the Cufon code after each AJAX request is complete and before the html is actually added to the page.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data);
Cufon.replace('h1');
$(this).slideDown('slow');
});
});
JavaScript is not executed because of a security reason OR beccause jQuery is just setting this element's innerHTML to some text (which is not interpreted as a JavScript) if it's contained. So the security is the beside effect.
How to solve it?
try to find all SCRIPT tags in Your response and execute them as fallows:
var scripts = myelement.getElementsByTagName("SCRIPT");
var i = 0;
for (i = 0; i < scripts.length; i++)
eval(scripts[i].innerHTML);

Categories

Resources