0

I have one task, when I open the html page, that html contains javascript under script tag, and under which I have implemented one function called auther(). How can I call this function while opening the html page, I don't want to implement it by using onClick or onLoad, etc. methods from html/javascript.

Means whenever my html gets executed my javascript function should get called itself. Following is my html:

<html>
   <head>
      <title>Demo</title>
   </head>
<body>
  <div id="authOps" >
      <button onclick="auther();">GET author</button>
      //By clicking on this button it is working but I want to execute 
      //this function when this html get executed
  </div>
</body>
<script type="text/javascript">
   function auther(){
      //some code
   }
</script>
</html>

In the above scenario whenever my html page is opened, the javascript function should get executed without any click handling.

Note : I have mentioned html code just for reference purpose, My main purpose just to execute javascript function, how can I achieve this??

1
  • the javascript function should get executed without any click handling, why would a handler run without the event being fired? and also servlet just spits out html, it doesn't do any html processing itself Commented Sep 23, 2017 at 9:39

2 Answers 2

1

There are 2 ways to do this as far as i know,

1:

<html>
   <head>
      <title>Demo</title>
   </head>
<body>
  <div id="authOps" >
      <button onclick="auther();">GET author</button>
      //By clicking on this button it is working but I want to execute 
      //this function when this html get executed
  </div>
</body>
<script type="text/javascript">
   function auther(){
	console.log("Hi");
   };
auther();
</script>
</html>

2:

<html>
   <head>
      <title>Demo</title>
   </head>
<body>
  <div id="authOps" >
      <button >GET author</button>
      //By clicking on this button it is working but I want to execute 
      //this function when this html get executed
  </div>
</body>
<script type="text/javascript">
   var thisIsAFunction = function (){
	console.log("Hi");
   }();
</script>
</html>

You can give a try with both options.

Sign up to request clarification or add additional context in comments.

Comments

0

Just call the method in a script block, instead of from the button click

<script>auther(); </script>

3 Comments

I also tried this, but on runtime browser is throwing exception saying undefined method
exact error is,"Uncaught ReferenceError: auther is not defined "
That's because you called it before it was declared. That's why it's working in @Gowtham Shivas first example

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.