Load the javascript file after loading the ajax - javascript

I am using jQuery and Ajax.
HOME.html
<html>
<head>
<script src="jquery.js"></script>
<script src="javascript.js"></script>
</head>
<body>
<div id="div1"></div>
<button>click</button>
</body>
</html>
javascript.js
$(document).ready(function(){
$('button').click(function(){
alert('Button is clicked');
$("#div1").load("test2.html");
});
$("#b2").click(function(){
$("#div2").hide();
});
});
TEST2.html
<body>
<div id="div2">
some content
<input type="button" id="b2" value="hide" />
</div>
</body>
<head><script src="javascript.js"></script></head>
When I click on button, Ajax loads the content in div. But when I again click on button then it is clicked twice. I know why this click twice happens, because I again load the javascript.js file.
If I can't do that then the hide button is not working because the JavaScript loads before the div2, that's why hide button is not working.
SOLUTION:
There is one solution is that I use the hide button code in test2.html instead of in javascript.js But I don't want to do that.
Beacuse this is a demo in my original code this is very difficult to do that.
Is there another solution to this?

Repeatedly re-loading the JavaScript is a bad idea.
If you just want to handle clicks on buttons that are dynamically added, you can do that using event delegation. Remove javascript.js from test2.html entirely, and hook up your handlers like this (e.g., change javascript.js to the following):
$(document).on("click", "button", function(){
alert('Button is clicked');
$("#div1").load("test2.html");
});
$(document).on("click", "#b2", function(){
$("#div2").hide();
});
That watches for the click event on the document, but only fires the associated handler if the event passed through an element in the bubbling phase that matches the selector in the second argument. When firing the handler, jQuery makes it look a lot like you had the handler actually attached to that element, rather than to document.
There's a lot more in test2.html than there should be. jQuery will only append the bit in the body (and run the script, but we're removing that). test2.html should just be:
<div id="div2">
some content
<input type="button" id="b2" value="hide" />
</div>
Side note: If you're going to replace it on the next click, I'd use $("#div1").empty() rather than $("#div2").hide() so that you actually proactively remove the content you're going to replace later, rather than just hiding it.

Related

Second page does not work with Codes in the first page

I have a main page that I have loaded another page on it via ajax when document is ready ,also I have a button that when I click It I shows an alert and, I have that button in the second page too. but when i click on it in that page that code does not work ?
how can i solve this problem ?
because I do not want to repeat js codes on the second page ?
here is my first page code :
first page code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="captcha" style="border:1px solid red;">
</div>
<div class="details1">cccc</div>
<script>
$(document).ready(function(e) {
$(".captcha").load("/secondpage.htm");
$(".details1").click( function()
{
alert('button clicked');
}
);
});
</script>
</body>
</html>
and this is my second page that I have loaded into div with classname captcha:
second page code:
<html>
<head>
</head>
<body>
<section class="details1"> Details </section>
</body>
</html>
When you need to create new elements on-the-fly, you can not use standard click etc. events. Dynamically created elements are not born with the same event handlers as the existing elements. You have to dynamically attach event handlers to newly created elements.
Replace 'click' with 'on'.
$("body").on("click", ".details1", function(){
alert('button clicked');
});

click event does not fire on newly created li tags

With the following code:
<!DOCTYPE html>
<html>
<head>
<title>test list</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<style>
li{
display:inline;
}
</style>
<body>
<input type="hidden" value="4" id="value">
<ol></ol>
<button id="btn2">increase</button>
<button id="btn1">show</button>
<p></p>
</body>
<script>
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
$("#btn2").click(function(){
var text="<li> -> kkk</li>";
$("ol").append(text);
});
$("#btn1").click(function(){
$("p").text($("li").length);
});
</script>
</html>
any newly created "li" tags that appear after clicking "increase" button, do not trigger handlers bound to the click event.
$("li").click(function(){
$(this).nextAll().css({"color":"red"});;
});
Can you please tell me the reason why it's not work. And is it possible to make it work? If yes, How? Thank you very much.
Try like this : As your 'li' are generating dynamically ( For further reading )
$("body").on('click','li',function(){
$(this).nextAll().css({"color":"red"});;
});
From jQuery documentation: "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next."
try this code:
$(document).on('click', 'li', function(){
$(this).nextAll().css({"color":"red"});;
});
May help to put your script library before the closing body tag
...
increase
show
...
see here: fiddle link
$(function() {
$("#btn2").click(function(){
var text= " --> ";
$('ol').append('<li>'+text+'</li>');
$('ol li:not(":first")').css('color','red');
});
$("#btn1").click(function(){
$("p").text($("li").length);
});
});

jQuery stops working after loading content into a div

For example I have the following HTML named index.html:
<html>
<head>
<style>
#content { float:left; }
#sub { float:right; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="action.js"></script>
</head>
<body>
<h2>Test de</h2>
<div id="content">
Content
<button class="loadSub">Load</button>
</div>
<div id="sub">
Sub content
</div>
</body>
</html>
And a simple JS file named action.js:
$(document).ready(function(){
$('button.loadSub').click(function(){
$('#sub').load('test.html');
});
$('button.hide').click(function(){
$('#sub').fadeOut('slow');
});
});
As you can see, when I click the button .loadSub the div #sub will be loaded with the new content from test.html:
<h2>This is the sub content</h2>
<button class="hide">Hide</button>
I got two problems here:
Firstly, the .loadSub button did successfully load the the div of id subcontent, but the .hide button did not work.
Secondly, after I had tried inserting
script type="text/javascript" src="action.js"
inside test.html, the hide button worked and faded out its content. But then in turn, I found out that the button loadSub no longer functioned. I couldn't load the subcontent again.
Is there any other way around to just once declare source of js file and make my button.loadSub work whenever I click it? Could anybody please explain the problem and give me a hint to fix it.
You're loading dynamic HTML into your page. This means that at the time you called $('button.hide').click(), the button.hide element did not exist in your page yet, so the click handler could not be attached.
You might want to try doing a delegate attachment instead.
$('#sub').on('click', 'button.hide', function () {
$('#sub').fadeOut('slow');
});
On the first page, put this. You can insert my JQQuery code into your action.js file. On the second page, the one you are loading into your div, put the second Jquery code I added.
On First page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<style>
#content{float:left;}
#sub{float:right;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(function(){
$('.loadSub').click(function(){
$('#sub').show();
$('#sub').load('test.html');
});
});
});
</script>
</head>
<body>
<h2>Test de</h2>
<div id="content">
Content
<button class="loadSub">Load</button>
</div>
<div id="sub">Sub content</div>
</body>
</html>
On the second page (the page that's loaded into the div, add this:
<script type="text/javascript">
$(document).ready(function(){
$(function(){
$('.hide').unbind("click").click(function(){
$('#sub').fadeOut('slow');
});
});
});
</script>
<h2>This is the sub content</h2>
<button class="hide">Hide</button>
The hide button isn't on the page when you try to bind the event so it is never registered.
Change it to use on like this (assuming version 1.7+)
$(document).on('click', 'button.hide', function(){
$('#sub').fadeOut('slow');
});
or delegate if an older version:
$(document).delegate('button.hide', 'click', function(){
$('#sub').fadeOut('slow');
});
This attaches the event handler at the document level so will work for any new content added to the page.

Move to a div after page load. "onmouseover" works but "window.onload" does not

I have a page (and divs) that are being dynamically generated and what I need for this page to do is to scroll to a particular div immediately after the page loads. What is screwy about this code is this...
The "button" code below, when you run the mouse over it (or onclick), works perfectly. It executes the rolldownTo function perfectly. However when I try to specify to specify the same action using window.onload, nothing happens. I have included both the "button " code and the window.onload below.
<html>
<head>
<title>Help</title>
<script LANGUAGE="JavaScript1.2" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js"
djConfig="usePlainJson : true, parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.window");
function rolldownTo(my_anchor){
dojo.window.scrollIntoView(my_anchor);
}
window.onload=rolldownTo('car_help');
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs /dojo/1.5/dijit/themes/claro/claro.css"/>
</head>
<body class="claro">
<div dojoType="dijit.layout.BorderContainer" style="width: 100%; height: 100%;">
<div dojoType="dijit.layout.TabContainer" region="center">
<div dojoType="dijit.layout.ContentPane" title="CAR HELP" selected=true>
<button type=button id=button1 onmouseover="rolldownTo('car_help');">
scroll to car_help
</button>
........
LOTS OF DIVS LIVE IN THIS DIV, INCLUDING MY TARGET "car_help"
........
</div>
<div dojoType="dijit.layout.ContentPane" title="BIKE HELP" selected=false>
........
........
</div>
</div>
</div>
<script language="JavaScript1.2" type="text/javascript">
.... LOTS OF CODE THAT GENERATES CONTENT FOR THE DIVS ABOVE
</script>
</body>
</html>
Does anyone have an idea why a Javascript event like onmouseover or onclick would work perfectly but window.onload will not?
Your problem is this line:
window.onload=rolldownTo('car_help');
You're not assigning the function rolldownTo to as the callback for the onload event, you're executing the function and assigning the return value, in this case undefined.
You need to wrap the call with an anonymous function in order to make it work:
window.onload = function(){ rolldownTo('car_help'); };
Now the anonymous function will get called by the onload event and then call rolldownTo.
So much for the problem, as NiL has halfway pointed out (onload fires after DOMLoaded) you can use dojo.addOnLoad instead of window.onload here, but you still have to use the anonymous function for the reasons stated above.
The page load doesn't mean the the DOM tree has been fully initialized which mean that your script cannot move the div unless the tree finish working, you must wait it until finished by using the javascript Event DOMContentLoaded.
In dojo, There is a function that can be called, it waits until the browser finish the DOM Tree, you can use it as :
dojo.addOnLoad(function(){rolldownTo('car_help');});
I hope this would work for you
Best Regards
NiL

Can a link have both an onclick jquery and javascript event?

I have a link that jQuery listens to, and if clicked it will toggle another div. The link also has an onclick javascript action. When I click the link, the div I want to toggle shows, but the javascript doesn't execute.
Is it possible to get the javascript to execute AND have jQuery toggle the div?
If so what would I put in the jQuery code to allow the link to execute the onclick javascript action?
jQuery script
$(function() {
$('#links a').live('click', function() {
$("#showall").toggle('slow');
});
});
my link
<div id ="links">
Play
</div>
for me the following is working in Chrome, Firefox and IE. Both pure Javascript (onclick) and jQuery click() get executed.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function() {
$('div').toggle();
});
});
</script>
</head>
<body>
Click me
<div>
Some div content...
</div>
</body>
</html>

Categories