-1

I want to run this script on pageload or after all the elements are loaded.

JavaScript

<script type="text/javascript">
    function backgroundload (){
          $(".portfolio-background-color")
              var color = /#[0-9\A-F]+/.exec($(this).html())[0];
              $(this).css('background', color)
      }
       window.onload = backgroundload;
</script>

i'm new to js please check if my code is okay and is it the correct way to load the js

Community
  • 1
  • 1
The Naga Tanker
  • 395
  • 1
  • 2
  • 12
  • 1
    Try it yourself and have a look at the browser console. You will see some errors. – str Jan 19 '17 at 07:32

1 Answers1

1

All Javascript runs on page load. If what you mean is that you want it to run after all the elements in the page have been initialized, there are several ways:

  • window.onload
  • document.onload
  • body.onload
  • $(document).ready

There are more in-depth explanations of the support for the first three, and the differences between them, here. Documentation for $(document).ready is here.

However, in my experience, the easiest way to ensure that a script runs after all synchronously-loaded content is simply to place the <script> element at the bottom of the <body>.

Community
  • 1
  • 1
furkle
  • 4,844
  • 1
  • 12
  • 22