Loading page into div causes page's javascript to not work - javascript

I am loading a page into a div by
<script>
$(document).ready(function() {
$("#link").click(function(e) {
e.preventDefault();
$("#div").load("page.php");
});
</script>
The page loads but the javascript that I have in page.php does not load.
This is what I have:
<script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
$(function() {
$("#date").datePicker();
});
</script>
When I load page.php outside of the div (as in its own tab/window), the page works perfectly. (The above is copy-pasta from http://jqueryui.com/datepicker).
What is the cause and how can I solve it?

Your scripts are never loaded. They are stripped out during load.
(The above is copy-pasta from http://jqueryui.com/datepicker/)
I'm going to assume that you mean you are copying the entirety of that sample's source, which looks roughly like this:
<!doctype html>
<html lang="en">
<head>
<!-- Snipped for brevity: A bunch of script and link elements-->
</head>
<body>
<p>Date: <input type="text" id="datepicker" /></p>
</body>
</html>
So you're taking this document using jQuery's load function and placing it inside a div:
$("#div").load("page.php");
Load won't cooperate here
According to the docs on .load():
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
In my own experience, this normally means that .load() will only return content from inside the body element, without the body element itself. In other words, from the above sample, this is the only HTML actually being loaded:
<p>Date: <input type="text" id="datepicker" /></p>
You should use your browser's developer tools (F12) to put a breakpoint in the script and find out what actually gets loaded.
How do you do this properly?
There's two parts to it.
Part 1: Move resources outside the <head> element
The Datepicker code sample contains a few resources in the <head>. You're going to have to place these elsewhere.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
The link elements
These can't be loaded up by the page you're loading. Place those inside the <head> element of the parent page you're trying to load this other one into.
The script elements
These will be loaded up when you load the document, too, as long as:
You place them within the <body> element of the document you're loading, and
You adhere to this section in the jQuery .load() docs to make sure you load in the script elements correctly.
However, it's only jQuery and jQuery UI, which you know you're going to be using. You might as well move these into the parent page's <head> element too.
2. Place the important bits you're trying to load in the body.
That's these bits:
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
Place those inside the <body> element of the document you're trying to load. Then, provided you followed that advice about scripts, this will be loaded successfully.
Optionally, include jQuery references in the <body>:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>

You may just need to change:
<script>
$(function() {
$("#date").datePicker();
});
</script>
to
<script>
$("#date").datePicker();
</script>
as the document.ready event has already fired, which is what $(function() { tells it to wait for. I'm not sure if jquery automatically runs scripts in ajax'ed content, if not, you could try this (not neccessarily safe, make sure you understand the security risks of eval if you do this).
$("#div").load("page.php", function() {
$("#div").find("script").each(function(i) {
eval($(this).text());
});
});
Note: this will run something like:
<script>
$("#date").datePicker();
</script>
But NOT something like:
<script>
$(function() {
$("#date").datePicker();
});
</script>
As, again, the second waits for the document.ready event, which has already fired.

I think $(document).ready() aka $(function) will not execute when you load the document with load.
You can try to trigger it manually in the complete callback of load, or you can name the function you pass to $ and call it.

Related

How I build code such http://fiddle.jshell.net/bwKZt/152/ - HTML & Javascript

I need build code such : http://fiddle.jshell.net/bwKZt/152/
but my code dosen't work ! I am a beginner. Please help me.
index.php:
<!DOCTYPE html><html>
<head>
<script>
$("#label").bind("keyup", changed).bind("change", changed);
function changed() {
$("#url").val(this.value);
}
</script>
</head>
<body>
<input type="text" id="label" />
<input type="text" id="url" readonly />
</body>
</html>
Some of the JavaScript here isn't native JavaScript , but is using a plugin called jQuery that makes searching and manipulating HTML elements easier.
When you see $(), that's the jQuery way of finding elements. But it won't work because you don't have jQuery referenced at all.
If you don't want to use jQuery, you can find elements with something like document.getElementById('label').
But lots of people use jQuery to make referencing page elements short and sweet, as with $('#label').
Try to reference jQuery first, like:
<!DOCTYPE html><html>
<head>
<!-- The below line references an externally hosted copy of jQuery 2.2.4 -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// The below chunk is telling it to bind to the keyup event only AFTER the document has fully loaded.
// Sometimes when your binding code is executed, the elements you wish to bind to aren't loaded yet.
$(document).ready(function(){
$("#label").bind("keyup", changed).bind("change", changed);
});
function changed() {
$("#url").val(this.value);
}
</script>
</head>
<body>
<input type="text" id="label" />
<input type="text" id="url" readonly />
</body>
</html>
The first problem is because you haven't include jquery with a script tag to solve that add this code in the head of you html file if you have the Internet connection to load Jquery from CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
or you can download Jquery file from Jquery site and you will have it locally
after that you must execute this code after the executing the jquery ready function
$(document).ready(function(){
$("#label").bind("keyup", changed).bind("change", changed);
function changed() {
$("#url").val(this.value);
}
})

JavaScript not working as an external file

I'm new to HTML, JavaScipt and everything related to programming, and I'm trying to create a simple page.
Now, I'm stuck with the following problem: I want to change the date of my main.html file, but the main.js is not working. I've already change the <script> position to inside the <body>, after the </span> and even after the </body>, without success. If the content of the main.js is within the HTML it works fine, but as a external file it doesn't.
Here is my main.html:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="main.js"></script>
<title>Page 1</title>
</head>
<body>
<p>WRF<br>
<span id="data">18/09/1987</span></p>
</body>
</html>
My main.js is just:
document.getElementById("data").innerHTML = "JUBA";
I've looked through the internet and through this forum, but all answers that I've found did not worked.
The files are on the same directory and the main.css works fine.
Thank you in advance.
At time you call main.js element #data was not created in DOM tree. You can fix this by putting the link to your Javascript file right before closing the body like this:
<script type="text/javascript" src="main.js"></script>
</body>
Document Object Model (DOM) is not "READY".
Try use onload event, inside main.js:
window.onload = function() {
document.getElementById("data").innerHTML = "JUBA";
};
If needs more "fast" than onload, use jquery with $(document).ready:
html:
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="main.js"></script>
main.js:
$(document).ready(function() {
$("#data").html("JUBA");
});
window.onload vs $(document).ready()
Answer by #Guffa:
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
The element is not yet accessible when you run the script.
Either you can put the script at the end of the page or delay the execution.
You could put the JavaScript in the <body> tag after the rest of the page. When the browser loads it, the <span> will already be there to be edited.
As per your code the script will be called first then page will be loaded, therefore when the script is running there will not be any element having id data because yet page have to be loaded. There are many ways to achieve what you need.
1. Add a script tag before or after end of body like
or
<script type="text/javascript" src="main.js"></script>
</body>
Write .js file above before body i.e. in head tag and write the whole javascript code in onload method.
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
<p>WRF<br>
<span id="data">18/09/1987</span></p>

Problems with jQuery Click

I'm having a bit of trouble with jQuery, and I really have no idea what I'm doing wrong.
I have a simple page with static content and a few buttons. My problem comes when I want to attach a click event to one of my buttons - it just won't work!
Here is the code I have in my html:
<head>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/my.js"></script>
</head>
<body>
....
<button class="btn btn-success" id="my-button">BUTTON</button>
</body>
And here is the code I have in my.js:
$('#my-button').click(function()
{
console.log("Button Clicked");
});
No matter how many times I click the button, no matter which browser I use the message is never entered to the console. I just don't get it, I've not had a problem like this before... I'm hoping it's not an obvious mistake.
I should also point out that when I change this to $(document).ready it works fine!!
Help :(
You said it your self, wrapping it in a document-ready callback will solve the problem.
The reason to this is that your JavaScript is run before the element actually is in the DOM, so at the time the JavaScript is run, no element match your selector, and therefor no clickevent-listener can be attached.
If you for some reason don't want to use a DOM-ready callback, another solution would be to include your JavaScript the last thing you do, just before you close your body element. When the browser get to that point, your element should be in the DOM, so your code should be fine.
Solution 1: Wait for DOM to be ready
$(function () {
$('#my-button').click(function() {
console.log("Button Clicked");
});
});
Solution 2: Load JavaScript last
<head>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
....
<button class="btn btn-success" id="my-button">BUTTON</button>
<script type="text/javascript" src="js/my.js"></script>
</body>
Try wrapping it inside document ready function like below,
$(function () {
//content below will be executed only after DOM is ready
$('#my-button').click(function() {
console.log("Button Clicked");
});
});
This is not a mistake. Problem is when your script runs, your button is not rendered on the page. When you wrap the script in $(document).ready(), it will ensure that the script runs only after the whole content is rendered correctly.
Your js precedes your html, which means the $('#my-button') selector comes up empty. You could try event delegation, to ensure no matter when an element that matches your criteria comes into existence, there is a click listener for it:
$(document).on("click",'#my-button',function()
{
console.log("Button Clicked");
});

Keeping javascript external - doesn't work

When i keep my javascript/jquery external, my code doesn't work. but when i combine them in my html file everything is fine.
any suggestions as to why this is?
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="program.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
with external javascript
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
VERSUS
<!DOCTYPE html>
<html>
<head>
<script type ="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
</script>
</body>
</html>
I guess you execute the click event before the DOM finishes loading. Wrap your code inside the dom ready event and it should work, Assuming your path to the external javascript file is correct.
$(function(){
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
});
Always use firebug (console) to see what is wrong with the script, if you run into any script errors.
Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...}); or moving your external javascript files to the bottom.
Wrap your js code in external file in
$(document).ready(function(){
//your code goes here
});
Right now you are including external js file in header and it is executed. At this point there is no elements so $('#clickme') and $("p") are empty set. In the second example you run this code after rendering html with that elements.
The reason that there is a difference, is that in the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit further...
Whilst a lot of people have mentioned using jQuery's document ready handler, I would like to point out that a workable solution is simply to move your script tags to the bottom of the page.
Not only will this solve your problem in itself, but it will also improve page load times because of how browsers treat scripts. When the browser encounters a script it stops everything else it is doing (known as a "blocking" operation), and parses and executes the script. This causes the page to just appear to stall from a user's perspective, meaning a bad user experience. Thus, because the scripts are parsed and executed only as they are encountered, by moving your scripts to the bottom you allow the browser to fully render the page so that the JavaScript does not block rendering.
Though rather than just moving scripts to the bottom of the page, I'd also follow what the others recommended and wrap the whole code in the document ready handler just to be extra safe that your code will always be executed at the correct time.
Also, in the debate of inline or external, external scripts are generally preferred as they are easier to maintain and the browser can cache them independently of the page (providing the correct HTTP headers are present).
To sum up here's some example code:
<html>
<head></head>
<body>
<!-- all your markup here -->
<!-- script at bottom, markup already rendered by this point -->
<script type="text/javascript" src="jquery.js"></script>
<!-- inline or external, still wrap in document ready handler -->
<!-- though external is better because the browser can cache it independently of the page -->
<script type="text/javascript">
//wrap in document ready to be extra safe
$(function() { /*code here*/ });
</script>
</html>

Basic jQuery .load Problem

I am trying to use jQuery's .load function to dynamically load content into my webpage. This seem so simple, but I cannot make it work. To try and figure it out, I made a test page with just basic structure, but the external content still won't load:
jquery.html
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$('#foo').load('test.html');
</script>
<div id="foo"></div>
</body>
</html>
test.html
<p>Text text</p>
I'm sure I have made a tiny error, but I can't find it anywhere!
You need to encapsulate your script in the $(document).ready() otherwise #foo won't exist when the script is executed:
<script>
$(document).ready(function(){
$('#foo').load('test.html');
});
</script>
You need to wait for the document to be ready before you can access the DOM. Just add a $(document).ready() around your original code:
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$(document).ready( function() {
$('#foo').load('test.html');
});
</script>
<div id="foo"></div>
</body>
</html>
or if you want a shorter code:
$(function() {
$('#foo').load('test.html');
});
Informally, what's happening is that, as your browser reads the code you wrote, it's drawing its contents as it goes along. When it reaches your <script> tag, it executes it. But when $("#foo") gets executed, the browser's still processing the <script> and hasn't reached the part of the code where you told it there's a div called foo, so the browser doesn't know it exists, and jquery will just find nothing.
Of course, the idea that the browser will just sequentially read your code and render it as it goes is naive at best, so while it might seem that just moving the <script> tag to the bottom of the code would work, you're not actually guaranteed it will work. Instead, the browser will notify you when it's done drawing the page by firing a load (and possibly a DOMContentLoaded) event. So all code that depends on the whole html being drawn should be executed in an event handler bound to those events.
jQuery makes waiting for the page to be loaded easy, just use something like this:
$.ready(function() {
doStuff();
});

Categories