user1110666
user1110666

Reputation: 171

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I have a working JavaScript function declared in the head of an HTML page. I know how to create a button and call the function when the user clicks the button. I want to call it myself some where on the page:

myfunction();

How do I do it?

Upvotes: 15

Views: 147236

Answers (4)

Minko Gechev
Minko Gechev

Reputation: 25682

You can call it like that:

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            var person = { name: 'Joe Blow' };
            function myfunction() {
               document.write(person.name);
            }
        </script>
    </head>
    <body>
        <script type="text/javascript">
            myfunction();
        </script>
    </body>
</html>

The result should be page with the only content: Joe Blow

Look here: http://jsfiddle.net/HWreP/

Upvotes: 30

Doug
Doug

Reputation: 7057

I'm not sure what you mean by "myself".

Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.

e.g. On page load:

<body onload="myfunction();">

Or on mouseover:

<table onmouseover="myfunction();">

As a result the first question is, "What do you want to do to cause the function to execute?"

After you determine that it will be much easier to give you a direct answer.

Upvotes: 4

harsimranb
harsimranb

Reputation: 2283

You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.

Upvotes: 1

j08691
j08691

Reputation: 207881

Just drop

<script>
myfunction();
</script>

in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

Upvotes: 3

Related Questions