Reputation: 177
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
Upvotes: 0
Views: 1868
Reputation: 653
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.
Upvotes: 1
Reputation: 221
Have you tried putting the changeIt()
call in the onload
event of the body?
<body onload="changeIt()">
<!-- Body here -->
</body>
Upvotes: 1
Reputation: 676
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.
Upvotes: 1
Reputation: 15053
Try running it on window load:
window.onload = function() {
changeIt();
};
Upvotes: 4