-3

How can I run javascript code just after page load, when page is loaded, it trigger, and when I go to another page it also trigger another piece of code for that page, how can I do it ?

7
  • window.onload = function() { // do something }
    – Weafs.py
    Commented Dec 24, 2014 at 8:34
  • read up jquery $(document).ready()
    – Aditya
    Commented Dec 24, 2014 at 8:35
  • 1
    @Aditya that is jquery.
    – Mr_Green
    Commented Dec 24, 2014 at 8:35
  • 3
    this is such a simple web search javascript page load. Please show some efort before posting rudimantary questions here
    – charlietfl
    Commented Dec 24, 2014 at 8:35
  • 1
    I mean why he will use jquery to load a page? isn't that overkill? @Aditya
    – Mr_Green
    Commented Dec 24, 2014 at 8:37

2 Answers 2

5

You can try

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>

    </body>
</html>

Click here http://jsfiddle.net/NEfR2/

0

document.ready() is a jQuery event. JQuery’s document.ready() method gets called as soon as the DOM is ready (which means that the browser has parsed the HTML and built the DOM tree). This allows you to run code as soon as the document is ready to be manipulated.

For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. However, IE can’t safely fire until the document’s readyState reaches “complete”, which is typically later.

You can find more info here (of course, this requires jQuery to be loaded)

1
  • 1
    Ready is not a method of document - it is as you pointed out - a function of the jQuery library which accepts the document as an parameter. $(function() { // Handler for .ready() called. }); does exactly the same. Commented Dec 24, 2014 at 8:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.