javaScript not working for page loaded by jquery load function - javascript

Page 1
<html>
<head>
<script src="jquery-1.8.3.js" type="text/javascript"></script>
</head></head>
<body><div id="main"></div> </body>
<script>$('div[id=main]').load('page2.php')
$('span[id*=temp]').on('click',function(){
alert(this.id); }); //this block of code not working!!
</script>
</html>
Page 2
<div>
<span id="temp">
this is demo
</span>
</div>
Basically i want to load page2 again in main div when tag is clicked but am not able to fetch the id of the tag in page one,script of page1 not working for page 2 items or tags

You are trying to bind the event right after the AJAX call, so the element doesn't exist yet. The call is asynchronous, so it doesn't stop the code execution to wait for the response.
Either bind the element after the content has loaded, using the success callback of the load method:
$('div#main').load('page2.php', function(){
$('span[id*=temp]').on('click', function(){
alert(this.id);
});
});
or use a delegate to bind the event to the parent element:
$('div#main').load('page2.php');
$('div#main').on('click', 'span[id*=temp]', function(){
alert(this.id);
});

Because you need to specify the parent selector to taking into account the elements created dynamicaly.
Exemple :
$("#main").on('click', 'span[id*="temp"]', function() {alert('Handler is working!');})
Here is a good related question : jQuery 1.7 on() and off() methods for dynamic elements

Related

Using .load in JavaScript

I am using .load() function in JavaScript and I'm working with JSP java files. I am loading a page like this in JavaScript
$("#body").load("livestatus #status")
The problem is the div I'm trying to load doesn't load immediately on page load because it contains some data from APIs, so there's a one second delay but my code doesn't accommodate that delay.
Try to put your code in document.ready block or if you are making an ajax request then put your code in Ajax success function
If you use jQuery and it just not initialized for some element, you can use
$(function() {
$("#body"). // ... your code
});
If it calls through some time and you can't track when exactly, you can use live listeners on some event. Like, click on this element.
$("body").on("click", "#body", function() {
// your code
});
$("body") can contain any parent element which had loaded before jQuery.
Or you can load 1px image with you code which loads after main code and track when it will load.
<div id="body">
<!-- your markup -->
<img class="loading-status-img" src="../path_to_1px_small_image.png" style="display:none">
<img class="loading-status-img-2" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII=" style="display:none">
<!-- your markup -->
</div>
<script>
$("body").on("load", ".loading-status-img", function() {
// execute you code here after #body will load
});
</script>
The second image is encoded with base64.
[UPD] old version of jQuery have another syntax. More: http://api.jquery.com/live/

Can't make jQuery callbacks to work properly while calling same function repeatedly

I have a simple share button aside every post, I'm using .toggle() function to show and hide the options. The code looks something like this:
<div id="posts">
<div class="post">
<div class="content">
Post content
</div>
<div class="share">
<div class="trigger"> Share </div>
<div class="hidden"> Share on Facebook </div>
<div class="hidden"> Share on Twitter </div>
</div>
</div><!-- each post -->
<div id="new">
</div><!-- new post container -->
</div><!-- Posts -->
<script>
function shareThis(){
$('.trigger').click(function(){
$(this).siblings().toggle();
});
}
$(document).ready(function(){
shareThis();
$('#new').load("/post2", function(){
shareThis();
});
});
</script>
I call this function once when the page loads, and then every time a new post is loaded.
The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded. I also tried this with 'each' function but same result.
So it's just working for the last call, similar to these question i found here and here, and some others, but didn't get a solution for my problem there.
Thanks!
The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded.
Your issue could be that you are binding the event twice (or as many number of times you load #new contents) to the existing .trigger by calling shareThis inside the load callback. So basically when you click on the old .trigger it will trigger the handler twice, i.e toggling it twice which keeps them in the same state. SO either bind the event to the newly added ones alone or turn the click event off and turn it on in the function shareThis:
function shareThis(){
$('.trigger').off('click').on('click', function(){
$(this).siblings().toggle();
});
}
You could also try:
function shareThis(ctx){
ctx = ctx || document;
$('.trigger', ctx).click(function(){
$(this).siblings().toggle();
});
}
$(document).ready(function(){
shareThis();
$('#new').load("/post2", function(){
shareThis(this);
});
});
Try binding the click to the document instead. Only need to do it once :)
$(document).on('click', '.trigger', function () {
$(this).siblings().toggle();
}).ready(function () {
$('#new').load("/post2");
});
http://api.jquery.com/on/
http://training.bocoup.com/screencasts/more-efficient-event-handlers/

Execute Jquery on div in ajax loaded contents

I have a page called forms.php with a javascript included in its head and a div called fadeinContents
i used Ajax to load part of a file called #sections1 into this div which works quite well
But i need to execute some Jquery on the loaded contents in the fadeinContents when they are clicked. Ive read other post but couldn't understand them well..
Here are my files
forms.php
<html>
<head>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/login.js"></script>
</head>
<body>
<div class="login_link">login</div>
<div class="signup_link">signup</div>
<div class="fadeinContents">
<!--Loaded contents goes here -->
</div>
</html>
Here's my Jquery
$(document).ready(function(e) {
$('#fadeinContents').load('forms.php #sections1');
$('.login_link').click(function(e) {
$('#fadeinContents').load('forms.php #sections1');
});
$('.signup_link').click(function(e) {
$('#fadeinContents').load('forms.php #sections2');
});
$('.recoverPassword').click(function(e) {
$('#fadeinContents').load('forms.php #sections3');
});
});
Loaded File containing
<div class="sections1">
<div class="signup">
<!-- Signup Forms Here -->
</div>
</div>
<div class="sections2">
<div class="login">
<!-- loginForms Here -->
</div>
</div>
<div class="sections3">
<div class="recoverPassword">
<!-- recover form Here -->
</div>
</div>
My problem is that the Recover password click function is not working because it was loaded, Please how can i make this work?
thnx in advance..
then you should bind that event differently. try it like this
$('.fadeinContents').delegate('.login_link', 'click', function(e) {
$('#fadeinContents').load('forms.php #sections3');
});
and so on for the rest of them.
This means that the click event is binded on the .fadeinContents but when triggered, it checks if the target is a .login_link and if so it will triggers the given callback. So delegating the event handler to a higher node will ensure that no matter when the content of the node will load/change or how many elements you have, if they match the criteria the event handler will trigger.
Delegating events is a bit more memory efficient as well. If you have for example one hundred cells you want to add click events to, doing a $(".cell").click( will attach a event listener on every one of them. Delegating it to the body for example with $("body").delegate('.cell', 'click', will only attach one event (and then do some looping and checking there, that's true) but you'll end up with only one event listener and it won't matter how many nodes you later add or remove. they will trigger that click event

Can I assign an action from javascript dynamically?

Typically, I do this to prompt the alert box, and say Hello
<div style="color:#00FF00" onclick=alert("Hello"); id = "helloDivTag">
<h3>This is a header</h3>
<p>This is a paragraph.</p>
</div>
But this time, I don't want to do it inside the html tag, I want to do it inside the js. How can I do so? Thank you.
i would recommend using the jquery framework then you just do this
$(function(){
$('#helloDivTag').click(function(){
alert("Hello");
});
});
implementing it would look like this you just put it in the header
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$(function(){
$('#helloDivTag').click(function(){
alert("Hello");
});
});
</script>
why i recommend using jquery and not simple javascript is because there is alot of other functionality that could get in handy almost everytime you want to do something
window.onload = function() {
document.getElementById('helloDivTag').onclick = function(){
alert('hi');
}
}
when the window loads the click event is attached to your div and whenever you do the clicks the alert happens. This is called seperating behvaiour from structure and style.

Javascript Ajax JQuery

Here's my issue.
I have a javascript function that update a div when i click the proper link. And it is working.
Since i have cliked the link my div content is updated with another Javascript. This time to close it.
Its fairly simple but i cant get it to work and i dont know why!
Here is the code that is in the page when it load for the first time
The div id config_window
<div id="config_window" class="config_window">
<div id="conception" class="conception">Conception et design graphique Zéro Gravité.
</div>
<div id="admin_btn"class="admin_btn">administration.</div>
<div id="test">test</div>
</div>
Now the Javascript that call for the update inside that div
<script language="javascript" type="text/javascript">
$("#admin_btn").click(
function(){
$('#config_window').addClass('config_open');
config_set('config_window','open','var')
}
);
</script>
So far it's working my div is getting updated and i see the new content. The new content is
<div id="conception" class="conception">Conception et design graphique Zéro Gravité.
</div>
<div id="admin_btn_x" class="admin_btn">Terminer.</div>
<script language="javascript" type="text/javascript">
$("#admin_btn_x").click(
function(){
$('#config_window').removeClass('config_open');
config_set('config_window','close','var')
}
);
</script>
i was expecting that same function to work but its not!! and i dont get why since the first one is.
Could it be becuse my second script is in the div that get updated??
Thanks!
I suspect it's because the element that the second handler is supposed to apply to doesn't exist until after the DIV is updated and the function applying the handler is executed before the DIV is updated -- therefore the handler is not applied. You might want to try using the live handlers for the click event so that it will apply to all elements matching the selector no matter when the element is added. You can add both handlers on page load and they will apply to the elements with those ids whether they are added dynamically or not.
<script type="text/javascript">
$("#admin_btn").live('click', function(){
$('#config_window').addClass('config_open');
config_set('config_window','open','var')
});
);
$('#admin_btn_x').live('click', function() {
$('#config_window').removeClass('config_open');
config_set('config_window','close','var')
});
</script>
Is there a reason you add divide the function into two scripts? I would change your script to something like this:
<script type="text/javascript">
$(document).ready(function() {
$('#config_window').hide(); // just in case
$('#admin_btn').bind("click", function() {
if($('#config_window').is(':hidden')){
$('#config_window').show();
config_set('config_window','open','var')
} else {
$('#config_window').hide();
config_set('config_window','close','var')
}
});
});
</script>

Categories