1

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

8
  • Are you executing your JavaScript before the page has finished loading? And if you're using jQuery, which it looks like, why are you using window.addEventListener('load', init, false);? Commented Oct 1, 2014 at 16:06
  • Keep in mind that the reference to the external js file must be placed after the JQuery reference, because it uses it... Commented Oct 1, 2014 at 16:08
  • Thats what $(document).ready(function() { .. }) is for Commented Oct 1, 2014 at 16:08
  • Put your script at the bottom of the body tag. That will be 'after' the page loads. Anything in the header is before the html content has loaded. Commented Oct 1, 2014 at 16:19
  • @j08691, I think adding the load event listener makes sure that the page finishes loading before the js execution, is it? In my production, I was not initially planning to use jquery, but will use the $ function as a utility function. Commented Oct 1, 2014 at 21:37

2 Answers 2

1

You only have to put the code inside jQuery document ready function, $() is a shortcut to that function:

$(function(){
    $('.myArea').css('background-color',"red");
});
Sign up to request clarification or add additional context in comments.

3 Comments

Your solution works. Can you please explain, why the add event listener is not working and your solution working?
this is the same as using ready() you cant bind events to elements that havent been rendered. ready() is an event on the document that fires when the document has loaded. read more here
Is as @Brian says, $() is a shortcut to $(document).ready()
0

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");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.