Adding CSS property on page load - javascript

I'm trying to add css property to an existing rule on page load. It works with onclick event but does not run when the page loads. Here is the code:
HTML
<ul id="list">
<li>aa</li>
<li>bb</li>
<ul>
<a onclick="changeIt(); return false" href="#">change background color</a>
CSS
li {
color: black;
}
Javascript (jQuery is not applicable in my case.)
function changeIt() {
var theRules = document.styleSheets[1];
theRules.insertRule("li{background-color: yellow;}", 1);
}
changeIt(); // doesnt run on page load

Try running it on window load:
window.onload = function() {
changeIt();
};

Your code probably doesn't work because the DOM is not ready when your function runs.
There are several ways to check if the DOM is ready before executing any code.
The most common way is to wait for the onLoad event to occur.
In your case that might look something like <body onload='changeIt();'>...</body>
One of the problems with waiting for onLoad is that if the page take a long time to load, execution of your code will be delayed.
And in fact the DOM can be ready even before the page has loaded. So another way to check DOM readiness is to use 'DOMContentLoaded' event, see http://www.javascriptkit.com/dhtmltutors/domready.shtml for more info.

You could always try
<body onload="changeIt()">
It's not the same functionality as the jquery document.ready, but it'll work after the body has loaded.

Have you tried putting the changeIt() call in the onload event of the body?
<body onload="changeIt()">
<!-- Body here -->
</body>

Related

On page load, jquery is running before a certain div has been created

I'm trying to do a .show() on page load, however, the div is not yet loaded
It looks like jquery is running before a certain div has been created.
Wondering how can I solve this ?
my code consists of the following:
<script>
function choose_category(category_id)
{
$('#' + category_id).show(); // this is the part which doesn't work, as on page load the div mentioned later is not yet available.
}
</script>
<script>
function load()
{
choose_category('<?php echo $model->category_id->__toString(); ?>');
}
</script>
<img onload="load();" src="http://media.sociopal.com/ires/images/homepage/status-socio-icon.png" alt="" width="0" height="0" style="display:none;"></img>
The html embeds php code which runs a loop and generates (among other divs) the following div:
<div id='thecategoryid!!' onclick='choose_category("51d552eb2c8751766000016d");return false;' class = 'settings_menu_item'>
<p class='settings_menu_item_text'>Design Channels<i class='icon-chevron-right right'></i></p>
</div>
However, as mentioned, when the page loads (only when the page loads) the .show() does nothing because it looks like the div is not yet created.
If I debug this in chrome and go step-by-step, there is no problem (the div is created on time and the .show() works fine)
Will appreciate your help.
I can see no error in the code you have posted.
It might be that your assumption of what $.show() does is wrong.
$.show simply removes any occurences of "display: hidden;" in the inline styling of the selected element/node.
<div style="color:red; display:none;">
would become
<div style="color:red;">
http://api.jquery.com/show/
Instead of using that inline onload stuff, try this giving your image an id (we'll use img here.
Since you are calling choose_category with an inline click event listener, do not place that function inside $(document).ready as it won't be able to be accessed.
Then, use the following JavaScript:
$(document).ready(function(){
var img = $("#img");
img.load(function(){
load();
});
if (img[0].complete)
img.load();
});
What this is doing:
When the doc is ready, get the image. Attach a load event listener. If the image has already loaded by the time we got here (especially with caches), trigger a load event anyway.
Also note that you shouldn't put special put exclamation points in your id.

How to execute code before window.load and after DOM has been loaded?

Here is the circumstance:
I have 2 pages:
1 x html page
1 x external Javascript
Now in the html page, there will be internal Javascript coding to allow the placement of the window.onload, and other page specific methods/functions.
But, in the external Javascript I want certain things to be done before the window.onload event is triggered. This is to allow customized components to be initialized first.
Is there a way to ensure initialization to occur in the external Javascript before the window.onload event is triggered?
The reason I have asked this, is to attempt to make reusable code (build once - use all over), to which the external script must check that it is in 'order/check' before the Javascript in the main html/jsp/asp/PHP page takes over. And also I am not looking for a solution in jQuery #_#
Here are some of the links on Stack Overflow I have browsed through for a solution:
Javascript - How to detect if document has loaded (IE 7/Firefox 3)
How to check if page has FULLY loaded(scripts and all)?
Execute Javascript When Page Has Fully Loaded
Can someone help or direct me to a solution, your help will be muchness of greatness appreciated.
[updated response - 19 November 2012]
Hi all, thanks for you advice and suggested solutions, they have all been useful in the search and testing for a viable solution.
Though I feel that I am not 100% satisfied with my own results, I know your advice and help has moved me closer to a solution, and may indeed aid others in a similar situation.
Here is what I have come up with:
test_page.html
<html>
<head>
<title></title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript" src="test_script_1.js"></script>
<script type="text/javascript" src="test_script_2.js"></script>
<script type="text/javascript">
window.onload = function() {
document.getElementById("div_1").innerHTML = "window.onload complete!";
}
</script>
<style type="text/css">
div {
border:thin solid #000000;
width:500px;
}
</head>
<body>
<div id="div_1"></div>
<br/><br/>
<div id="div_2"></div>
<br/><br/>
<div id="div_3"></div>
</body>
</html>
loader.js
var Loader = {
methods_arr : [],
init_Loader : new function() {
document.onreadystatechange = function(e) {
if (document.readyState == "complete") {
for (var i = 0; i < Loader.methods_arr.length; i++) {
Loader.method_arr[i]();
}
}
}
},
load : function(method) {
Loader.methods_arr.push(method);
}
}
test_script_1.js
Loader.load(function(){initTestScript1();});
function initTestScript1() {
document.getElementById("div_1").innerHTML = "Test Script 1 Initialized!";
}
test_script_2.js
Loader.load(function(){initTestScript2();});
function initTestScript2() {
document.getElementById("div_2").innerHTML = "Test Script 2 Initialized!";
}
This will ensure that scripts are invoked before invocation of the window.onload event handler, but also ensuring that the document is rendered first.
What do you think of this possible solution?
Thanking you all again for the aid and help :D
Basically, you're looking for this:
document.onreadystatechange = function(e)
{
if (document.readyState === 'complete')
{
//dom is ready, window.onload fires later
}
};
window.onload = function(e)
{
//document.readyState will be complete, it's one of the requirements for the window.onload event to be fired
//do stuff for when everything is loaded
};
see MDN for more details.
Do keep in mind that the DOM might be loaded here, but that doesn't mean that the external js file has been loaded, so you might not have access to all the functions/objects that are defined in that script. If you want to check for that, you'll have to use window.onload, to ensure that all external resources have been loaded, too.
So, basically, in your external script, you'll be needing 2 event handlers: one for the readystatechange, which does what you need to be done on DOMready, and a window.onload, which will, by definition, be fired after the document is ready. (this checks if the page is fully loaded).
Just so you know, in IE<9 window.onload causes a memory leak (because the DOM and the JScript engine are two separate entities, the window object never gets unloaded fully, and the listener isn't GC'ed). There is a way to fix this, which I've posted here, it's quite verbose, though, but just so you know...
If you want something to be done right away without waiting for any event then you can just do it in the JavaScript - you don't have to do anything for your code to run right away, just don't do anything that would make your code wait. So it's actually easier than waiting for events.
For example if you have this HTML:
<div id=one></div>
<script src="your-script.js"></script>
<div id=two></div>
then whatever code is in your-script.js will be run after the div with id=one but before the div with id=two is parsed. Just don't register event callbacks but do what you need right away in your JavaScript.
javascript runs from top to bottom. this means.. if you include your external javascript before your internal javascript it would simply run before the internal javascript runs.
It is also possible to use the DOMContentLoaded event of the Window interface.
addEventListener("DOMContentLoaded", function() {
// Your code goes here
});
The above code is actually adding the event listener to the window object, though it's not qualified as window.addEventListener because the window object is also the global scope of JavaScript code in webpages.
DOMContentLoaded happens before load, when images and other parts of the webpage aren't still fully loaded. However, all the elements added to the DOM within the initial call stack are guaranteed to be already added to their parents prior to this event.
You can find the official documentation here.

Javascript Error onload image fadeIn

I am getting an inconsistent error with my script. Often times everything works fine, however, every now and then I am getting the following error: ReferenceError: fadeIn is not defined
Here is the relevant code:
In the <head>
<script type="text/javascript" charset="utf-8">
window.fadeIn = function(obj) {
var item = $(obj).parent();
item.fadeIn(1000);
}
</script>
In the <body>
<div class="item" style="display:none"><img onload="fadeIn(this)" src="/uploads/thumbs/{{image.url}}"><br>{{ image.description }}</div>
Again, The images are loading and fading in most of the time but every now and then I get the error and the images do not fade in.
Is there a better way to approach this? Or just something I'm missing?
You need to make sure your code is loaded after the DOM is ready.
window.onload = function(){
var fadeIn = function(obj) {
var item = $(obj).parent();
item.fadeIn(1000);
};
};
... that's a partial fix, but not really, because in all likelihood, your <img/> tags with the onload hardcoded into them is going to try to fire that method before it's available.
Since you're using jQuery anyhow, you should look at something like this:
$(function() {
$(".item img").load(function(){
$(this).fadeIn(1000);
});
});
and get rid of the hardcoded onload from your img tags.
It should be noted, also, that there are caveats listed on the .load() API page:
From the docs (http://api.jquery.com/load-event/):
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
A better solution might be to hide the images with CSS, then after the load event is fired, fade them in.
(Even better than that might be to let browser behavior be, as your results may be mixed, and users seeing a blank page might instead hit the reload button thinking their browser glitched, before your animations are complete. ... just a friendly warning that these kinds of DOM manipulations can sometimes have unintended side-effects on user behavior!)
You can try defining the Handler directly in the Script instead of assigning it in HTML..
Javascript
<script type="text/javascript" charset="utf-8">
$(function() {
$('img').load(function() {
var item = $(this).parent();
item.fadeIn(1000);
});
});
</script>
HTML
<div class="item" style="display:none">
<img onload="fadeIn(this)" src="/uploads/thumbs/{{image.url}}">
<br>{{ image.description }}</div>
You're missing a document ready, so jQuery is'nt loaded, and the fadeIn function is'nt defined. Even if the image is loaded, there is no guarantee that jQuery is loaded aswell.
You're also actually calling your function fadeIn, while jQuery already has a function called fadeIn, and even though they have a different namespace it does seem like a bad idea to me.
nPlease ensure you have correct link to JQuery javascript file. You can use Google's hosted library for an example or create your own copy of this .js file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
min.js file can be found at download section of JQuery official website. Save it and place into the website folder. And link it like:
<script src="/js_folder/jquery-1.8.2.min.js"></script>
Another option with Jquery:
<div class="item" style="display:none">
<a href="http://docs.jquery.com/">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif">
</a>
<p>image name</p>
</div>​
Script:
<script type="text/javascript">
$(document).ready(function() {
$('.item').delay('1000').fadeIn('1000');
​ });​
</script>
http://jsfiddle.net/CYGNp/1/

onload and Jquery ready(). Do they work on any DOM? such as table or div?

I need to put a dynamic content on a div using javascript script. This div is on the top of the page so it will load first before other things below it. And there are really lot's of things down there. So, when I put the script on the ready() or onload, the div will be empty for 2 -3 seconds while other things are displayed. So, I tried putting the onload or ready() to this div.
//example div, which is on the header part of the page
<div id="cont1">
something goes here
</div>
//... and there are a lot of other things going down here.
I tried putting the onload="alert('test')" on the div tag
<div id="cont1" onload="alert('test')">
and also the jquery method
<script>
$("cont1").ready(function(){
alert("test");
});
</script>
Both methods don't work, as the alert is triggered only after the whole page is displayed.
but if I put the alert("test"); script immediately after closing the above div, it works fine (as the other things on the page is not displayed yet when the alert is showing).
<div id="cont1">
something goes here
</div>
<script>
alert("test");
</script>
But this method is kind of a bad design isn't it? So, any other way to achieve this?
If you want a javascript action to fire after a specific DOM element has loaded, simply place it immediately after the element, as you noted:
<div id="cont1">
something goes here
</div>
<script>
alert("test");
</script>
Some may disagree, but this is not bad design. As long at whatever occurs in this script pertains only to elements which occur prior to it in the HTML document, everything should be kosher. The DOM is loaded linearly in the order it appears in the document, so there is no case in which the script coming after #cont1 would occur prior to #cont1. If the script is lengthy, you could put it in a function in a header include then call the function there instead.
onload and the meta-event of "ready" apply the the entire DOM document, not just any DOM node, which is what you are attempting here.
I would stick with jQuery's $(document).ready(...) for code that requires the DOM to be present.
onload is unfortunately on the window only.
However, I have written a jQuery plugin called waitForImages that will fire a callback when images have loaded inside any container.
This is a bit half way but you can have a img of a single pixel same color as the background at the end of the div and have an onload on the img.

Difference between onload() and $.ready?

Can you list the difference between onload() and $(document).ready(function(){..}) functions in the using jQuery?
the load event (a.k.a "onload") on the window and/or body element will fire once all the content of the page has been loaded -- this includes all images, scripts, etc... everything.
In contrast, jquery's $(document).ready(...) function will use a browser-specific mechanism to ensure that your handler is called as soon as possible after the HTML/XML dom is loaded and accessible. This is the earliest point in the page load process where you can safely run script that intends to access elements in the page's html dom. This point arrives earlier (often much earlier) than the final load event, because of the additional time required to load secondary resources (like images, and such).
The main differences between the two are:
Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery's ready event will get executed once the HTML structure is loaded without waiting for the resources.
We can have multiple document.ready() in a page but Body.Onload() event cannot.
Document.ready() function triggers as soon as HTML DOM loaded. But the onload() function will trigger after HTML DOM, all the body content like images loaded.
body.onload() cares about both HTML structure and assoicated resources where as document.ready() cares only about the HTML structure.
onload() fires when all the content (everything) on the targeted eleement is fully loaded like CSS, images etc.
$.ready indicates that code in it need to be executed once the targeted elements content loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
.
Ex(body onload):
<body onload="loadBody()">
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body
Ex(onload on an element):
<img src="w3html.gif" onload="loadImg()" width="100" height="132">
<script>
function loadImg() {
alert("Image is loaded");
}
</script>
Ex3 ($.ready):
<script type = "text/javascript">
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
Onload take care about DOM and resources: it checks if images are loaded, script are ready to run and much more.
$.ready simply check if we have read the full DOM of the page.
Please check out this link for more explain and example: http://dailygit.com/difference-between-document-ready-and-window-load-in-jquery/

Categories