Calling javascript function when html is executed - javascript

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??

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.

Just call the method in a script block, instead of from the button click
<script>auther(); </script>

Related

Why the function doesn't alert onclick?

I'm not too sure why the code below doesn't work in the browser. Any ideas?
<!DOCTYPE html>
<html>
<script>
function click() {
alert("You clicked on a paragraph");
}
</script>
<body>
<p onclick="click()" id="paragraph">This is a paragraph</p>
</body>
</html>
I figured out how to do the above with the document.getElementById function (see below).
<!DOCTYPE html>
<html>
<script>
function click() {
alert("You clicked on a paragraph");
}
</script>
<body>
<p id="paragraph">This is a paragraph</p>
</body>
<script>
document.getElementById("paragraph").onclick = function() {
click();
}
</script>
</html>
My question is why the first approach doesn't work?
Your first function doesn't work because click() is a built-in function in JavaScript which simulates a mouse-click on an element. Here is a demo. So when you click on the paragraph the built-in function is executed first instead of your function which displays the message through alert() function
Since your second function is an anonymous function it executes without any error.
To solve it simply rename it to any other name except the name of a built-in function. Refer the code snippet below for example.
<!DOCTYPE html>
<html>
<body>
<script>
function alertOnclick() {
alert("You clicked on a paragraph");
}
</script>
<p onclick="alertOnclick()" id="paragraph">
This is a paragraph
</p>
</body>
</html>
Went through your Code #sb2021
I think it is well resolved by #rifkyniyas
But I would like to give you a suggestion.
Try to place the script tag inclusions just before the closing of body tag. Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.
Something just like this
<body>
.
.
.
.
.
.
<script>...</script>
</body>
Check this out

A button on my page takes me to Google, using pure Javascript, how do I wait for it to load?

I have the following html code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Soemething</h1>
<button id='btn'>Take me to Google</button>
<script>
document.getElementById('btn').addEventListener('click', doStuff);
function doStuff() {
window.location.assign("https://www.google.com/");
}
</script>
</body>
</html>
How do I wait for Google to load before executing code on google.com such as doing a search?
Thank you
Your script's sandbox is only the page whether it is executing. Once, you are redirected to google.com, your script will become invalid.
Your only option is to get the page via AJAX and run a callback function to execute when the content is loaded.

alert is executing before html loads

Hello my questions is about how a webpage is loaded! Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
alert("Why?");
</script>
</body>
</html>
I cannot for the life of me figure out why the alert is running before the heading is displayed. It is my understanding that since the alert is right above the closing body tag it will be the last thing run. Why is the page waiting for me to close out the alert before displaying the heading?
Thanks for the help!
Edit: I ran this code in firefox rather than chrome and it worked how I wanted it to - the heading displayed first before the alert ran.
You need to execute your script after the page loads with
<body onload="script();">
An external script will execute before the page loads.
<body onload="script();">
<h1>Waiting</h1>
<script type="text/javascript">
function script() {alert("Why?");}
</script>
</body>
You can use setTimeout() to show the alert after a few seconds (when the page should have loaded).
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
setTimeout(function(){
alert("Why?");
}, 1000);//wait 1000 milliseconds
</script>
</body>
</html>
You can check if the header (the h1 tag) is there and only alert if it is there.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1 id="header">Waiting</h1>
<script type="text/javascript">
var x;
x = setInterval(function(){
if(document.getElementById("header")){
alert("Why?");
clearInterval(x);
}
}, 100);
</script>
</body>
</html>
The simplest workaround code without using JQuery I could write is this. Please check it.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
window.onload = function(){
setTimeout(()=>{
alert("Why?");
},10)
}
</script>
</body>
</html>
The cleanest way to do this seems like it would be to put your javascript in a separate file, and load it with the defer attribute. This will cause it to fire after the DOM loads (technically, just before DOMContentLoaded, but it doesn't work consistently across browsers unless there is a src attribute, which is why you would need to move it to an external file.
<script src="myScript.js" defer></script>
Oddly, adding some CSS to your heading could also affect this since JS is supposed to execute in order after any pending CSS.
The timeout function or a $(document).ready() function will do what you need in theory, but a timeout could need to be adjusted based on the complexity of the page, and if you aren't already using jQuery, you probably won't want to add it just to use $(document).ready().

Calling an alert function from a button but without using onclick

What im trying to do, is to call my function from whenever someone clicks on my button. However, i know that it can be done with
<button onclick="myFuntion()>
But i want to skip that step, i dont want a function in my button, i've heard that its bad programming.
However, heres how my file looks.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javacript" src="javascript.js"> </script>
<title> Javascript </title>
<script>
function testFunction(){
document.getElementById("test").onclick = Hello;
}
function Hello(){
alert("Hello");
}
</script>
</head>
<body>
<button type="button" id="test" <!-- I know i can use onclick="testFunction()" here but i dont wanna !-->> Click me </button>
</body>
</html>
So how come it doesnt pop-up with the box "Hello" whenever i push the button, what have I done wrong?
You have to call your testFunction after the HTML body is loaded so that it actually creates he binding.
That is, at the end of the file, you'd do something like:
...
<script>
testFunction()
</script>
</body>
...
If you run that binding code in your head script the button element won't exist yet — that is why this have to be at the end.
JavaScript libraries such as jQuery make this more elegant by providing an ready hook, where one puts code to be called once the page is fully loaded, without having to resort to code on the bottom of the page.
Complete example with script at end (confusingly, Stack Snippets don't show it to you in the order they actually are in the snippet; even though it doesn't look like it, the script is at the end here):
// Scoping function to avoid creating unnecessary globals
(function() {
// The click handler
function Hello() {
alert("Hello");
}
// Hooking it up -- you *can* do it like you did:
//document.getElementById("test").onclick = Hello;
// ...but the modern way is to use addEventListener,
// which allows for more than one handler:
document.getElementById("test").addEventListener(
"click", Hello, false
);
})();
<button type="button" id="test">Click me</button>
window.onload=testFunction;
function testFunction(){
document.getElementById("test").onclick = Hello;
}
function Hello(){
alert("Hello");
}
Just run the line in your testFunction always. As seen here:
https://jsfiddle.net/arugco4b/

What's wrong with this javascript/HTML

I think I just need a second pair of eyes on this one. The div's onclick event doesn't seem to be working. Any ideas?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title="My First Program"/>
<script type="text/javascript">
window.onload = function(){
window.alert("If you see me then the page has loaded");
click();
}
//we do programming here
/*because
it is
fun*/
window.alert("Helo World!");
function click(){
window.alert("CLICK!!!!");
}
</script>
</head>
<body>
<div>This web page will run my first program</div>
<!--this will be awesome-->
<br>
<br>
<br>
<div id="d1" onclick="click()">Click me</div>
</body>
Also, for the reccord, this is not my first program.
your html is malformed. the title tag needs to look like this:
<title>My First Program</title>
Also, you seem to have a naming conflict because you named your function the same thing as a built-in function. rename your 'click' function to 'myclick' or something else.
Once you fix that, everything else should be good.
When something is going weird, the first thing you should always do is validate your markup.
http://validator.w3.org/check
Here is the complete, working version of the markup.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My First Program</title>
<script type="text/javascript">
window.onload = function(){
window.alert("If you see me then the page has loaded");
click();
}
//we do programming here
/*because
it is
fun*/
window.alert("Helo World!");
function myclick(){
window.alert("CLICK!!!!");
}
</script>
</head>
<body>
<div>This web page will run my first program</div>
<!--this will be awesome-->
<br>
<br>
<br>
<div id="d1" onclick="myclick()">Click me</div>
</body>
Every time I see a question like this anywhere, the typical answer I give is "don't use the Netscape model for event handling".
Give this a read - http://www.quirksmode.org/js/introevents.html
Update: Looks like "click" isn't a very good name for a function, since it's already registered for events and such, which is likely why it didn't work. I should have caught that.

Categories

Resources