JQuery event binding - javascript

I'm loading from DB some html (using ajax post request), it looks like:
<div id="slides_control">
<div>
</div>
</div>
With html I also load JS-code:
<script>
$('#slides_control a').bind('click', function() {
alert('achtung');
});
</script>
Script goes right after the html (in received data).
But when I click at some link inside new html, I don't see the alert. What's wrong?
I also tried to bind it after ajax ended:
$.post('page.php', {}, function(data) {
document.write(data);
$('#slides_control a').bind('click', function() {
alert('achtung');
});
});
Didn't help me.

You probably running bind function before your html has been loaded, so it does not find element
So, put your code to run on dom load:
$(function(){
$('#slides_control a').bind('click', function() {
alert('achtung');
});
}):

Try wrapping the jQuery call:
<script>
$(function(){
$('#slides_control a').bind('click', function() {
alert('achtung');
});
});
</script>

execute this script when data is loaded. You are executing this script before data is loaded.

Related

how can i load an external html and make it work with jquery

I want to load an external html to my actual html with load but not triggered by click. I want to load it on page on document ready event. I did like this but the jquery doesn't apply to the loaded content.
<script>
$(document).ready(function(){
$( "#rezervations" ).load("http://websoftit.ro/wayoutz/calendar.php");
});
</script>
I mean content is loaded but the jquery from the main doc doesn't work for the loaded content. Example for script that should work on loaded content
<script>
$(".table").on("click", "td", function() {
$(this).closest("tr").siblings().removeClass("td_select");
$(this).toggleClass("td_select");
});
</script>
Ok then you might need to write it as below:
$( "#rezervations" ).load("http://websoftit.ro/wayoutz/calendar.php",function(){
$(".table").on("click", "td", function() {
$(this).closest("tr").siblings().removeClass("td_select");
$(this).toggleClass("td_select");
});
//Your other initialization here
});
i have checked it and there is not problem with your code its working fine just check that you have particular div with id rezervations.
$(document).ready(function(){
$( "#rezervations" ).load("http://websoftit.ro/wayoutz/calendar.php");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="rezervations">HELLO</div>
Regards
Example loading a header:
$(document).ready( function(){
$("header").load("http://localhost/js/header.html", function() {
$('body').trigger('headerReady');
});
});
From the api: https://api.jquery.com/trigger/ , then
$('body').on('headerReady', function(){
//do ur stuff here
});

jQuery Loads .aspx Page But Doesn't Execute the Script Inside

i'm trying to load .aspx page using jquery like this;
$('ul#menu li ul.collapse').on('click', 'li a', function (e) {
e.preventDefault();
var div = $('#content .container-fluid .row-fluid .span12');
var url = $(this).attr('href');
setTimeout(function () {
var htmlPage = div.load(url + ' #MainContentHolder',
function () {
//other stuff
});
}, 1000);
});
However, my .aspx page does have javascript embedded like this;
<div id="MainContentHolder">
<h1>Test Aspx Content</h1>
<div>
<script type="text/javascript">
alert("hello");
</script>
</div>
</div
When, i see the resulted HTML, i can see the it is loaded (using firebug). But it's not showing the alert() message
I have also read all other questions on stackoverflow but it's not helpful on this to me;
UPDATE: As suggested in asnwer, following code only works for the first time. I tried to turn off the cache:false and also tried from GET to POST;
$.ajax({
url:url,
success:function(data){
div.html(data);
}
});
$('ul#menu li ul.collapse').on('click', 'li a', function (e) {
e.preventDefault();
var div = $('#content .container-fluid .row-fluid .span12');
var url = $(this).attr('href');
setTimeout(function () {
$.ajax({
url:url,
success:function(data){
div.html(data);
//other stuff
}
});
}, 1000);
});
var htmlPage = div.load(url + ' #MainContentHolder',
function () {
//other stuff
});
As per the documentation of .load(),
If .load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed.
Instead you may want to take your script in js file and use $.getScript(), which will load a JavaScript file from the server using a GET HTTP request, then execute it.
Edit:
Alternate way is to have only script in your page and load that page as shown in below link
jQuery .load() call doesn't execute javascript in loaded html file
OR
As already suggested use $.ajax() and in success callback function, you need explicitly execute your JS code as shown in this post. Use eval.
OR
You can load your dynamic page using .load and in success callback function use $.getScript as already suggested earlier.
I hope it helps!

ajax html in div

In my html code i have this
<li class="register">Registreer</li>
and
<div id="content">
</div>
I try to load a html file into the div using the following code in the head
<script type="text/javascript" src="includes/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="includes/js/navbar.js"></script>
navbar.js :
$(document).ready(function() {
$(function(){
$(".register").click(function(){
$("#content").load("/signup.html");
document.write("test");
});
});
});
I have copied signup.html all over my webpage folders. But it does not work.
However it does display test for 1/4th of a second.
I also tried putting my js code directly in the html file but that doesn't work either.
$(document).ready(function () {
$(".register").click(function(){
$("#content").load("/signup.html");
return false;
});
});
By returning false from the click event the hyperlink element will know not to perform its default action (which is why the page is refreshing).
You are repeating yourself:
$(document).ready(function() {
$(function(){ //same as $(document).ready(function() {
$(".register").click(function(){
$("#content").load("/signup.html");
document.write("test");
});
});
});
Try just doing this:
$(function(){
$(".register").click(function(){
$("#content").load("/signup.html");
document.write("test");
});
});
Also you might want to try stopping the default event of your link:
$(function(){
$(".register").click(function(){
$("#content").load("/signup.html");
document.write("test");
});
$(".register").on('click', 'a', function(e){
e.preventDefault(); //prevents action of the link
});
});
When using a relative URL, the URL is relative to the page on which the JavaScript is run. In your case, since you are using the string '/signup.html', It will look for the singup.html file up one directory from the directory of the page currently being viewed.
Use the F12 Development Console in IE or Chrome, FireBug, of Fiddler to view your AJAX requests and results to see whether your 'singup.html' is being loading from the appropriate directory. You can also view source after the load completes to see if there is HTML beiing loaded into your DIV.

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

Reload javascript file after an AJAX request

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!

Categories

Resources