Reputation: 33
I have a div area that I want to change the css after the page loads. My HTML looks like the following
<div class='myArea'>
</div>
<script type="text/javascript">
$('.myArea').css('background-color',"red");
</script>
And it works. But if I move this to an external js file and reference the js file from the header, this doesn't work. The following is the js code in the external file -
function init(){
$('.myArea').css('background-color',"blue");
}
window.addEventListener('load', init, false);
What might be the reason behind this
Upvotes: 1
Views: 68
Reputation: 4578
You only have to put the code inside jQuery document ready function, $() is a shortcut to that function:
$(function(){
$('.myArea').css('background-color',"red");
});
Upvotes: 1
Reputation: 29121
Try this instead?:
window.onload = function() {
$('.myArea').css('background-color',"red");
}
Or, if you're already using jQuery, you could use their document ready(): http://api.jquery.com/ready/
$( document ).ready(function() {
$('.myArea').css('background-color',"red");
});
Upvotes: 0