I'm new to JavaScript and I'm sure that this is a very trivial fix.
I'm dynamically changing a div content based on which button is clicked. This example works in JSFiddle but however when I put it on my PC it simply loads the entire webpage even when I wrap the JS with $(window).load(function(){ ... })
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Misc</li>
</ul>
<div id="about" class="menu-content">About</div>
<div id="contact" class="menu-content">Contact</div>
<div id="misc" class="menu-content">Misc</div>
</body>
</html>
My JS (script.js):
$(window).load(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
$(window).load(function(){ ... })
replace by :
$(document).ready(function(){ ... })
Replace your (window).load to (document).ready
load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.
load()
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.
ready()
While JavaScript provides the load
event for executing code when a page
is rendered, this event does not get
triggered until all assets such as
images have been completely received.
In most cases, the script can be run
as soon as the DOM hierarchy has been
fully constructed. The handler passed
to .ready() is guaranteed to be
executed after the DOM is ready, so
this is usually the best place to
attach all other event handlers and
run other jQuery code. When using
scripts that rely on the value of CSS
style properties, it's important to
reference external stylesheets or
embed style elements before
referencing the scripts.
try this
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$('div', $content).hide();
$('div[data-menu-content='+type+']').show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
You can try below solution :
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
When i ran your snippet in my PC, I found out that Jquery was not able to find div, based on the selectors you have specified at the time of loading.
Related
I'm new to jQuery.I have learned that DOM content will be loaded first and then window.onload event will occur as all the style sheets and images have to be loaded.
But this doesn't turn out for me with the following code
<!DOCTYPE html>
<html>
<head>
<title>Add Event Listener</title>
<script type="text/javascript" src="../jquery-3.2.1.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
alert("DOM Loaded");
});
$(window).on("load",function(){
alert("Window Loaded");
});</script>
</head>
<body>
</body>
</html>
After Opening this on Google Chrome (63.0.3239.108) I'm getting an alert that Window is Loaded prior to the alert of "DOM Loaded".
Same problem with Microsoft Edge (40.15063.0.0)
But,this works fine with Firefox(57.0.3)
Can anyone explain this?
Thanks in advance !
This Question is not a duplicate of
window.onload seems to trigger before the DOM is loaded (JavaScript)
That is because you test it without any image to load...
So all the markup has been parsed and all loaded. So the load event occurs.
Then when the script has been parsed, the ready occurs.
It usually is the script that is parsed faster, when there is images to load.
See below what happens when there is one.
$(document).ready(function(){
alert("DOM Loaded");
});
$(window).on("load",function(){
alert("Window Loaded");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://static.pexels.com/photos/132037/pexels-photo-132037.jpeg">
They are events and are triggered by a state being achieved. They are not interdependent events, so they have no fixed order.
window.onload fires once all resources declared in the html document are downloaded.
document.onload fires once the dom is built.
They are not dependent on each other. The dom can be built prior to the last resource being downloaded. All of the resources could download prior to the dom being built.
My goal is to load javascript in the <head> only if a certain element exists in the <body>.
However, I have a problem: I am loading a Web Component, which is just a <script> hosted elsewhere and is pulled in as:
<script src="https://someurl.com/some-web-component.min.js"></script>
This web component file is huge, so I don't want to pull it in unless it is inserted into body by our Content Management System (CMS).
The constraints I am working under are:
• The <head> is shared between pages, so I need conditional logic
• I have no control over the <body> inserted by the CMS, which will potentially contain the <my-web-component> tag
• I NEED the script to load the web component, so I can't use jQuery's $(document).ready, at least I think I can't - an error will be thrown because the browser won't know the element exists
This plunker partially shows my problem, minus all the web component complexity:
https://plnkr.co/edit/GGif2RNHX1iLAvSk1nUw?utm_source=next&utm_medium=banner&utm_campaign=next&p=preview
Any way around this?
You can use DOMContentLoaded event.
The DOMContentLoaded event is fired when the initial HTML document has
been completely loaded and parsed, without waiting for stylesheets,
images, and subframes to finish loading.
In this case you can look for the Component and add the script with something like the following
document.addEventListener("DOMContentLoaded", function(event) {
if(document.querySelector('Component')){
var script = document.createElement('script');
script.src = 'https://someurl.com/some-web-component.min.js';
document.head.appendChild(script)
}
});
Probably a better approach though would be to add the script in the head with async attribute and later remove it if the component is not found.
Something like this
<script async src = "https://someurl.com/some-web-component.min.js"> </script>
<script >
document.addEventListener("DOMContentLoaded", function(event) {
if (document.querySelector('Component') == null) {
var script = document.querySelector('script[src="https://someurl.com/some-web-component.min.js"]')
document.head.removeChild(script)
}
});
</script>
More about DOM lifecycle events
More about async script loading
I am using $(document).ready and inside this method checking if element exists or not. It is working completely fine for me. Below is code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Test Element Exists or Not</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var elem = document.querySelector('h1');
var isElemPresent = !!elem;
console.log('Is the element present: ', isElemPresent);
});
</script>
</head>
<body>
<h1>Hello Plunker!</h1>
<script>
var elem = document.querySelector('h1');
var isElemPresent = !!elem;
console.log('Oh NOW it works...: ', isElemPresent);
</script>
</body>
</html>
I am not sure where you are facing issue while using jQuery. There might be some other issue. Above approach is good enough to load script after checking if element is present.
Plunker link:
https://run.plnkr.co/preview/cjgczwlzt000knneldv5d52ea/
Why is $(document).ready needed after the <script> tag?
What would happen if we don't use $(document).ready?
$(document).ready is javascript code, so it has to be written in <script> element and after jQuery is loaded.
If you don't write $(document).ready, your code will not wait for DOM to load completely and execute the javascript code immediately.
If you're using script in <head> that is using/manipulating some elements from DOM, you'll need ready, otherwise you'll get null/undefined.
If you're using script at the end of <body>, then you'll be safe as all the elements are loaded.
Quoting as it is from jQuery Docs
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
Example? Sure!
In Head no ready
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
alert($('#myname').val());
</script>
</head>
<body>
<input type="text" value="Tushar" id="myname" />
</body>
</html>
At the end of body
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" value="Tushar" id="myname" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
alert($('#myname').val());
</script>
</body>
</html>
In head with ready
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
alert($('#myname').val());
});
</script>
</head>
<body>
<input type="text" value="Tushar" id="myname" />
</body>
</html>
For the <script> at the end of <body>, you can omit ready.
Why is $(document).ready really need after <script> tag when we use javascript.
It isn't.
What else if we don't use $(document).ready
First, understand why people use ready: It's used to delay the code within the function you pass into it until jQuery calls that function, which jQuery does when it thinks the document is fully loaded.
JavaScript code within script tags runs immediately. If the script tag is above an element it refers to, the element won't exist when the script runs:
<script>
$("#foo").show();
</script>
<div id="foo" style="display: none">...</div>
That div will not be shown, because it doesn't exist when the code runs. So people use ready to delay their code.
There's a better way if you control where your script tags go: Just put your script tag at the end of the document, just before the closing </body> tag:
<div id="foo" style="display: none">...</div>
<!-- ... -->
<script>
$("#foo").show();
</script>
</body>
All of the elements defined above the script tag will exist when the code runs. No need for ready.
The ready event occurs when the DOM (document object model) has been loaded.
Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.
//Use ready() to make a function available after the document is loaded:
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});
Like in the example above.
The ready() method specifies what happens when a ready event occurs.
Direct quote from Learn jQuery
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $( window ).load(function() { ... }) will run once the entire
page (images or iframes), not just the DOM, is ready.
I wrote a small page with jQuery and an external .js file. But it won't load the jQuery part. Here my Code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/testScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<button id="testBtn">Oh my Goood...</button>
<div id="testDiv">testText</div>
</body>
</html>
And here is my external Script:
alert("no jQuery");
$("button#testBtn").click(function(){
alert("Works!");
});
As you can see, jQuery will load before all other scripts. The alert pops up fine. But if I click the button, nothing happens. If I put the script inside the html document directly, the button event works as expected.
I reviewed these questions: Link and Link. But still not working as expected.
Instead of using the $(document).ready() method, you could also just move your javascript references to the bottom of the page, right above the </body> tag. This is the recommended way to include javascript in webpages because loading javascript blocks the page rendering. In this case it also makes sure the elements are already rendered when the javascript is executed.
You'll need to add the click function inside document ready.
$(document).ready(function(){
$("button#testBtn").click(function(){
alert("Works!");
});
});
Your method fails because the code is being executed as the page is being loaded and the elements it refers to haven't been loaded yet. Using $(document).ready holds the function execution till the DOM elements are ready.
I have a page that looks like this..
<!DOCTYPE html>
<html>
<head>
<title>JQM</title>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.css">
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.js"></script>
<script>
$(function(){
$('[data-role="list-divider"]').toggle(function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
</div>
<div data-role="content">
</div>
</div>
</body>
</html>
I am adding html in dymanically from the server in the content area. The problem is that when I add the content dynamically, the jquery function that I created statically on the page doesnt engage..
<script>
$(function(){
$('[data-role="list-divider"]').toggle(function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
</script>
If I add the html statically all the code works fine and everything is good. My question is how do I make this jquery available to run once html is added to the page from the server?
I DID THIS AND IT WORKED, is there a more elegant way using .on or is this fine?
//got html blob
deferred.success(function (res) {
$(function () {
$('[data-role="list-divider"]').toggle(function () {
$('.' + $(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
}, function () {
$('.' + $(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
});
Since the jquery is currently ran when the document is ready and your content is not loaded yet it won't find the elements and wire-up the events. Adding your script to the ajax.success should solve your problem.
looking at your code, I don't see where you're loading the content dynamically. But if you want that script to run. You should try a document.ready() in front of that script
You can't bind event handlers to elements that haven't been created. Check out this:
http://api.jquery.com/on/
Try this:
$(function(){
$(document).on('toggle', '[data-role="list-divider"]', function(){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});
Haven't tested it though. For on('click') this usually works.
What you do is you bind the 'toggle' trigger to the whole document ( $(document) ) and then check on what element is was triggered. This way you can detect elements that were created after the initialization of the DOM.
You have to use jquery .On() method to attach even handlers to contents dynamically added to pages. Check this - .on
Some thing lik this might work (didn't test) :-
$(function(){
$('[data-role="list-divider"]').on('toggle' ,function(event){
$('.'+$(this).attr('data-link')).addClass('show');
$(this).children().removeClass('ui-icon-plus').addClass('ui-icon-minus');
},function(event){
$('.'+$(this).attr('data-link')).removeClass('show');
$(this).children().removeClass('ui-icon-minus').addClass('ui-icon-plus');
});
});