<div class="actions">
<h3>Actions</h3>
<ul>
<li>Configurations</li>
</ul>
</div>
<script type="text/javascript" src="/jquery.min.js"></script>
<script type="text/javascript">
$('ul a').click(function(){
alert("");
});
</script>
In the above code is document.ready necessary. What i mean is, is there any case when js will be executed before html
.ready is a shortcut to DOMContentLoaded (or onreadystatechange or an assortment of workarounds for other browsers). That event fires when the DOM has been built - in other words, when the whole HTML has been downloaded.
So, as long as your script tags are the last thing before </body> (they are not inside any divs or other elements) the end result is the same, you don't need $(document).ready. That is even recommended, since putting your scripts in the <head> will slow down the loading of content.
Though I'd recommend you to adopt this pattern, to avoid problems with the $ global:
<script>
(function($){
$('ul a').click(function(){
alert("")
})
})(jQuery)
</script>
These other questions are interesting reads:
How does jQuery's "document ready" function work?
Does putting scripts on the bottom of a web page speed up page load?
When do you choose to load your javascript at the bottom of the page instead of the top?
Benefits of loading JS at the bottom as opposed to the top of the document
In your case, it seems there is no problem.
But, when you use pictures (<img />), there is a possibility for the document to execute your function (it fires "ready" event) even if the pictures aren't displayed yet.
Related
I built a site for a client where I have a script which moves a sidebar div below the main content when in mobile view. This script is loaded in the footer:
// Move Global nav to top for mobile
$(window).on("resize", function() {
var windowSize = $(window).innerWidth();
if(windowSize > 767){
$(".utility-nav").insertBefore($(".global-nav"));
$(".sidebar-secondary").insertAfter($(".subnav"));
} else {
$(".global-nav").insertBefore($(".utility-nav"));
$(".sidebar-secondary").insertAfter($(".content-main"));
}
}).resize();
They are adding a third party calendar which requires them to insert code snippets that include inline scripts. When these are placed in the .sidebar-secondary div, which is moved for mobile, the content disappears. I assume that, since my script is running after these have initiated, they are being canceled out.
Is there a way to just have my script rerun any inline scripts within that div?
Here is the page they are testing:
http://www.umary.edu/sandbox-training/index.php
The scripts in the left sidebar are the ones that are malfunctioning.
Thank you!
You can retrieve all the script tags within your div and eval the text inside them
$('#run').click(function(){
$('#someSideBar').find('script').each(function(){
eval( $(this).text() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someSideBar">
<script type="text/javascript">
alert('hello');
</script>
<script type="text/javascript">
alert('there');
</script>
</div>
<input type="button" id="run" value="Run">
** You should research the security implications of this before proceeding.
The reason your content disappears is because the <iframe>s that hold your content are unloaded when they are detached from the DOM, and loaded upon attaching them to the DOM again. Since the <iframe>s in question seem to be generated by a script, the second load yields an empty document. See this simple DOM test-case for seeing that load/unload bevhavior. As far as I can tell there is no way to move an iframe in the DOM in such a way that this behavior is prohibited.
You explicitly ask for this, but simply rerunning the inline <script>s may not yield the results you hope for, unless these scripts are (accidentally or purposefully) written in such a way that allows this. Be very careful with this sort of stuff. If there is a single document.write() your entire document would be overwritten. This is usually not the kind of destructive power you'd want to hand to a third party script.
You could try rearranging your content using Flexbox and the order property, so content is moved in CSS and not the DOM.
You could try rearranging the other content in such a way that you don't need to move .sidebar-secondary in the DOM. You may need to split the secondary content block into a separate <div role="complimentary"> (btw. that's what <nav> is for). Once that is done, you can move #content-start before the container of .sidebar-secondary.
I'm just messing with some javascript and I came across something that puzzled me a little.
I've added a link to a script file into the header of a document, just after the link to jQuery.
If I place in the test file:
(function($){
$("#thing").mouseover(function(){alert("woo");});
})(jQuery);
The mouseover event does not trigger the function.
However, if I add
(function($){
$(document).ready(function(){
$("#thing").mouseover(function(){alert("woo");});
});
})(jQuery);
The event does work.
Is it simply that without $(document).ready the DOM hasn't finished loading at the point when my self-executing function runs, so there is no #thing yet to attach the function to or is there another explanation?
I've added a link to a script file into the header of a document
This is the point.
Usually people put script files in the footer of document to optimize the process of loading the page, therefore it would not need to wait for the document to be ready to execute something based on the DOM already loaded (if you are in the footer, you have already loaded the rest - unless you have some content loading async).
Try putting your script file in the footer, and you will not need the $(document).ready.
Summary: In your case you need it, because when the script starts executing you have not started yet looking for the DOM, and the element cannot be found in that time.
It's because document ready waits until the document has fully loaded before executing.
Anything that binds to DOM elements must be done when the document is fully loaded otherwise those event handler bindings will be trying to bind to DOM elements which don't yet exist.
So yes, you answered your own question.
$( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute
It waits for the entire HTML excepts the Images.
some times you noticed that you recived an error “$ is not defined.” then in that case
you can use $( document ).ready()
You can just move the $ to make it work
$(function(){
$("#thing").mouseover(function(){alert("woo");});
});
Demo
Explanation $(function(){}); is equivalent to $(document).ready(function(){}); in jQuery
The document ready function waits for the page to load and
then executes whatever is in there. This prevents immature
actions before the page loads.
As a thumb rule, remember this,
$(document).ready(function(){
//jQuery code goes here
});
Apparently this works for me
<div id="body">
<section class="featured">
<div class="content-wrapper">
...
</div>
</section>
</div>
#section scripts{
<script type="text/javascript">
(function ($) {
$(".featured").mouseover(function () { alert("woo"); });
})(jQuery)();
</script>
}
it is basically a immediately executing function.
I included a script into my document's head that contains the following jquery code:
$('.unappreciatedIcon').click(function() {
alert('JS Works!');
});
In the body of my document I have following:-
<span class="unappreciatedIcon">.....</span>
But there is no alert displayed when I inserted the script into the document head from an external js file. When I had put this script in body simply below the target elements this worked flawlessly.
Thanks to you all:
I am getting this to work with the following code:
$(document).ready(function(){
$('.unappreciatedIcon').click(function() {
alert('fds');
})
});
Did you wrap your jquery in a $(document).ready(function() { // your code // }); ?
If not your jquery code is executing immediately and the browser has not loaded your span. You need to wait for the document to be ready (using the code above) before assigning events.
Update
$(document).ready(function() {
$('.unappreciatedIcon').click(function() {
alert('JS Works!');
});
});
When your script ran, it looked for an element having the class unappreciatedIcon. Nothing was found because the document is still being parsed and there was no node having the class unappreciatedIcon available in the document so far. The DOM is being constructed incrementally.
But when you put your script after the span element occurs, then $('.unappreciatedIcon') was found because it has been parsed and added to the DOM, so the click handler was tied to it.
Either run your code in a ready callback. The ready callback basically runs when the entire HTML has been parsed and the DOM is fully constructed which is usually a safe point to start running your JavaScript code that depends on the DOM.
$(document).ready(function() {
$('.unappreciatedIcon').click(...)
});
or put your code after the element occurs (don't need to wrap it inside the ready callback in this case),
<span class="someClass">..</span>
..
<script>
$('.unappreciatedIcon').click(...)
</script>
just going to go with basics but did you make sure to include the jquery library? If it doesn't work and it's in the code you can also open in firefox with firebug go to the console tab and see what error you have.
The javascript is being processed before the page has finished rendering. As Erik Philips suggested, you need to put this statement inside your $(document).ready() function to ensure the page is loaded before the statement is evaluated.
$(document).ready(function(){
$('.unappreciatedIcon').click(function() {
alert('JS Works!');
});
});
here is the fiddle http://jsfiddle.net/Pf4qp/
Since HTML loads from top to bottom, the head loads before the rest of the page. You could solve this problem by putting the link to your js file right before the end tag. However, its generally better practice to put the javascript link in the head.
A better alternative is to use the defer attribute in the script tag.
For example:
<script type="text/javascript" src="script.js" defer></script>
or
<script type="text/javascript" src="script.js" defer="defer"></script>
The second option is kind of unneccessary though. This attribute is pretty well supported. Internet Explorer has supported it since version 5.5 though apparently it is "buggy" through IE9. It has been fully supported since FireFox 3.5, Chrome 8.0, Safari 5.0. It also works with all current mobile browsers. I guess it is not supported by any Opera browsers though.
Disclaimer: I am new to jQuery.
I am trying to implement a fadeOut effect in jQuery for a div block, and then fadeIn effect on two other div blocks.
However, these effects are only working in the Chrome browser (i.e. they won't work in Safari, FireFox, Opera) which is rather perplexing to me. I have tried clearing my cache in case it was storing an old file, but none of that seemed to do anything.
Basic idea (stored in mainsite.js file):
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300);
$("#videoPlayer_XYZ").delay(300).fadeIn(100);
$("#videoHiddenOptions_XYZ").delay(300).fadeIn(100);
});
So when a div tag with the id of videoThumbnail_XYZ is clicked, it starts the fadeOut and fadeIn calls on the other div tags.
I am loading my javascript files into the page in this order (so jQuery is loaded first):
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script async="" type="text/javascript" src="javascripts/mainsite.js"></script>
Any guidance you could give is greatly appreciated!
Make sure the DOM is fully loaded before your code runs.
A common way of doing this when using jQuery is to wrap your code like this.
$(function() {
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300);
$("#videoPlayer_XYZ").delay(300).fadeIn(100);
$("#videoHiddenOptions_XYZ").delay(300).fadeIn(100);
});
});
This is a shortcut for wrapping your code in a .ready() handler, which ensure that the DOM is loaded before your code runs.
If you don't use some means of ensuring that the DOM is loaded, then the #videoThumbnail_XYZ element may not exist when you try to select it.
Another approach would be to place your javascript code after your content, but inside the closing </body> tag.
<!DOCTYPE html>
<html>
<head><title>your title</title></head>
<body>
<!-- your other content -->
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script async="" type="text/javascript" src="javascripts/mainsite.js"></script>
</body>
</html>
If mainsite.js is being included before your div is rendered, that might be throwing the browsers for a loop. Try wrapping this around your click handler setup:
$(document).ready(function(){
// your function here
});
That'll make sure that isn't run before the DOM is ready.
Also, you might consider putting the fadeIn calls in the callback function of your fadeOut, so if you decide to change the duration later on, you only have to change it in one place.
The way that'd look is like this:
$("#thumbnailDescription_XYZ").fadeOut(300,function(){
$("#videoPlayer_XYZ").fadeIn(100);
$("#videoHiddenOptions_XYZ").fadeIn(100);
});
I see you have a delay set to the same duration your fadeOut is, I would recommend instead of delaying which in essence your waiting for the animation to complete that instead you use the callback function.
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300, function() {
$("#videoPlayer_XYZ").fadeIn(100);
$("#videoHiddenOptions_XYZ").fadeIn(100);
});
});
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.
$(document).ready(function(){
$("#videoThumbnail_XYZ").click(function () {
$("#thumbnailDescription_XYZ").fadeOut(300);
$("#videoPlayer_XYZ").delay(300).fadeIn(100);
$("#videoHiddenOptions_XYZ").delay(300).fadeIn(100);
});
});
All three of the following syntaxes are equivalent:
* $(document).ready(handler)
* $().ready(handler) (this is not recommended)
* $(handler)
I have some tracking code that the provider (WebTraxs) says should be placed at the bottom of the tag. The problem is that this same code is causing everything on the page (including my jQuery code) to run AFTER the WebTraxs is executed. This execution sometimes takes long enough where images rollovers, etc aren't working because the user is mousing over images before WebTraxs has finished.
Therefore, I'm trying to add the needed tags (from WebTraxs) to the body after the page is loading in the document ready handler, using the following:
setTimeout(function(){
var daScript = '<script language="JavaScript" type="text/javascript" src="/Scripts/webtraxs.js" />';
var daOtherScript = '<noscript><img alt="" src="http://db2.webtraxs.com/webtraxs.php?id=company&st=img" />';
$('body').append(daScript);
$('body').append(daOtherScript);
},
5000);
I have two problems with the above:
In Firefox, after 5 seconds, it page goes completely blank.
In IE, there's no errors thrown, but normally you can see the WebTraxs code trying to load a tracking image in the status bar. This is not occurring with the above code.
Is there a better way to accomplish my objective here? I'm basically just trying to make sure the WebTraxs code is executed AFTER the document ready handler is executed.
Why don't you use the .getScript function:
setTimeout(function(){
$.getScript("http://path.to/Scripts/webtraxs.js");
},
5000);
What it's really curious about your code is that you add a <noscript> tag using JavaScript... it does not make any sense. If the user does not have JavaScript the setTimeout won't be fired, thus it <noscript> content won't be displayed.
I'm basically just trying to make sure the WebTraxs code is executed AFTER the document ready handler is executed.
In that case, you just have to do this:
$(document).ready(function(){
$.getScript("http://path.to/Scripts/webtraxs.js");
});
You don't have to use jQuery's DOMReady event handler. The reason people use DOMReady is that it allows the full DOM to load before firing up scripts that manipulate the page. If you call your scripts too early, parts of your page may not be accessible -- for example, if you call them before <div id="footer">...</div>, they won't be able to see $('div#footer') because it's not been pulled into the DOM yet. And that's great, except that your DOMReady methods will always execute after any in-page scripts have executed first. That's why your webtrax code is getting executed first.
But you can get the same benefits of DOMReady and still control the order of execution by calling your page scripts at the end of your document, when there's nothing left but HTML closing tags. They will be executed in the order they appear.
So try this instead:
<html>
<head>
<script type="text/javascript" src="myPageScripts.js"></script>
</head>
<body>
<div id="pagesection1"></div>
<div id="pagesection2"></div>
<div id="pagesection3"></div>
<!--NO MORE CONTENT BELOW THIS LINE-->
<script type="text/javascript">//<![CDATA[
runMyPageInitializerScripts();
//]]></script>
<script language="JavaScript" type="text/javascript" src="/Scripts/webtraxs.js" ></script>
</body>
</html>
In this script, runMyPageInitializerScripts() would still have complete access to #pagesection1, pagesection2 and pagesection3, but would not see the final script tag. So the page isn't in exactly the same condition as when DOMReady is fired, but for most scripts usually there is no downside.
<script> tags cannot use a shortcut like <script/>.
You have to use <script></script>
Anyways, I don't understand where the difference is on executing those scripts on DOMready or after a specific amount of time. If it blocks the UI it will do the same after 5 seconds no?
You are missing the closing </script> and </noscript> tags.
If you want to keep the <script> tag you may need to escape it (not sure if this persists on newest browsers, but as far as i remember you can't have <script> tags inside a script tag), take old google analytics code as example:
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
Splitting the script tag also works:
document.write("<scr"+"ipt src='somescript.js'></sc"+"ript>");
But since you're using jQuery, .getScript() is your best option.