Calling an alert function from a button but without using onclick - javascript

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/

Related

click(jquery) executes the function as soon as script is loaded and doesn't responds to clicks

I was trying to execute a function using .click (jquery 3.4.1) when a button is pressed but the function executes as soon as the page loads. And after some trying I thought there might be some piece of code that is making it behave this way so I created new files with basic elements and tried using it but it still didn't work. I thought I might be doing something wrong and so I checked a tutorial but it didn't help because I was doing the same thing.
I tried .on('click', function) too but the result was same.
The .html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1 style="text-align: center;">Some Text</h1>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
The .js file
$('h1').click(console.log('Clicked'))
Any idea why it isn't working?
You are attaching a click event listener to the h1
$('h1').click(console.log('Clicked'))
What is does is it executes the console and what it returns is assigned to the event listener. So that is why it is not working. You basically just did the following because console does not return anything.
$('h1').click(undefined)
so you have to assign it a function
$('h1').click(function () { console.log('Clicked') })
// Your original way written out to see what is happening
// $('h1').click(console.log('Clicked')) // code below is same thing as this line
var cl = console.log("Clicked Original Way") // will log message
console.log('cl is:', cl) // cl is: undefined
$('h1').click(cl) // aka $('h1').click(undefined)
// solution 1
$('h1').click(function() {
console.log('Clicked')
})
// solution 2
function myClickFunction() {
console.log('Clicked w/ function')
}
$('h1').click(myClickFunction)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 style="text-align: center;">Some Text</h1>
Since the argument you're passing in is not a callable function, jQuery is unable to call it when the click actually happens. Try something like this:
$(document).ready(function() {
$('h1').on('click', function(e) {
console.log('clicked');
});
});
click expects a function
$('h1').click(function() {
console.log('Clicked');
});
The way you are doing it, is to output 'Clicked' and have a undefined handler "sent" to click().
Check out the documentation here

Why use window.onload

I have tried finding an answer to this on my own, but only found instructions on how to use onload events. I seem to be missing the point.
I've been taught that if I want something to happen when the page loads, I should use window.onload like this:
<script>
window.onload = dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
But now that I am thinking on my own I wonder what the point of doing that is. Because this also produces the same result:
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
Anything I put at the top inside <script> is going to execute anyway... so what's the point of window.onload?
If you're directly running your code with dosomething();, you're delaying your browser's rendering for the time it takes your JavaScript code to run.
You can try to insert your code to the <head> of your html document:
<!DOCTYPE html>
<html>
<head>
<script>
dosomething();
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body>
Does not render before the alert is dismissed!
</body>
</html>
You'll see that the page stays blank until you dismiss the alert. So every second the browser takes to run your JavaScript code is a second that your users have to wait for the site to be rendered.
Now if you change the code to be run on body's onload, the page gets rendered before the alert is shown:
<!doctype html>
<html>
<head>
<script>
function dosomething()
{
window.alert('hello');
}
</script>
</head>
<body onload="dosomething()">
This page gets rendered before the alert!
</body>
</html>
Consider these two blocks of code:
<head>
<script>
alert(document.getElementById('foo').value);
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
<head>
<script>
window.onload = function() {
alert(document.getElementById('foo').value);
}
</script>
</head>
<body>
<input id="foo" value="hello">
</body>
In the first example, we'll get an error because the element you are referencing isn't found when the script runs - and so you are trying to get value of null.
In the second example, document.getElementById() will find the element with the id foo, because window.onload will get fired only when the complete DOM has been loaded and so the element is available.
window.onload will fire once the DOM has finished loading. In your example, the DOM is not required. However, the following code will fail if the DOM has not yet loaded:
function doSomething() {
alert(document.getElementById('test').innerText);
}
// Throws: TypeError: Cannot read property 'innerText' of null
Assuming your page contains an element with id test, it will alert its text.
waiting for the onload event assures you that all of your scripts and resources are loaded
Assume you are using jquery in your page and you invoked a function that uses it directly without onload , you can't guarantee that the jquery file has been loaded, which will lead to errors and possibly ruining your whole logic
The onload event is handy to make sure the page is fully loaded before you run a script. For your example above it doesn't make sense, but if your page is still loading an item on the bottom and you try to call it then nothing will run.
I recommend using jQuery and using the ready function. This way you will ensure your page is completely loaded.
$( document ).ready(function() {
// This will only run after the whole page is loaded.
});
If you don't want to load query, just put your javascript at the bottom of the page. It's best practice, and ensures the DOM is loaded in full.
For more info on the jquery ready function go here: https://api.jquery.com/ready/

reference to function before its defined

I have read that if you want to make it look like your site loads faster then you should put your javascript at the end of your html file like the following
<html>
<body>
</body>
<script>
//my awesome javascript functions go here because it lets things load faster
//than if it was at the top
</script>
</html>
The problem is when I create buttons or use onChange events that call these functions.
How am I meant to keep my JS at the bottom of the page and have the JS defined for when it reads that the js function will need to be called?
For example
<html>
<body>
<input type="text" onChange="myfunction()"/>
</body>
<script>
function myfunction(){}
</script>
</html>
I did the code in pseudo code-ishly so you wouldn't focus on any of my syntax errors, but more focus on how I am meant to go about this.
When creating the page, it creates the html properly, but gives me a console error saying "myfunction" is not defined.
If I move the script part above the body this works, but it is recommended to keep it last to increase speed in page load.
Just a note I am not using jquery.
I originally thought this was a duplicate (Javascript at the bottom, function call in the body?) but it doesn't seem to answer my problem.
------------------------update----------------------------
using event listeners
<html>
<body>
<input type="text" id="myawesometext"/>
</body>
<script>
function myfunction(){}
element = document.getElementById('myawesometext');
element.addEventListener("onChange", myfunction, false);
</script>
</html>

Loading .js file in <head>

So I am new to javascript (in fact, new to programming in general).
My question is, can I consider loading the .js file in the
<head><script src="script.js"></script>...</head>
as loading a header file (like in c/c++)?
I guess not. Suppose my script.js looks like this:
function copyToClipboard(text)
{window.prompt("Copy to clipboard: Ctrl+C, Enter", text);}
and my index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<textarea id="a" autofocus="true"></textarea>
<script> onclick=copyToClipboard(document.getElementById("a").value);
</script>
</body>
</html>
It does not work, namely, it does not wait for my clicking (which means that the function is loaded correctly-it is called successfully, it is just that the pop-up does not wait for the mouse event). But if I put the script in-line, it works:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea id="a" autofocus="true"></textarea>
<script>onclick=function copyToClipboard(text) {
window.prompt("Copy to clipboard:Ctrl+C,Enter",document.getElementById("a").value);
}
</script>
</body>
</html>
The reason why the first code doesn't work is that you're calling the copyToClipboard() function and assigning the return value to the onclick variable. In the second code you're correctly assigning it a function reference instead of calling the function immediately.
In other words:
onclick = copyToClipboard(document.getElementById("a").value);
"Call copyToClipboard(), assign return value (undefined) to the onclick variable"
onclick = function copyToClipboard(text) { ...
"Assign a reference to a function called copyToClipboard() to the onclick variable"
To make it work with the function definition in an external script, wrap the function call in an anonymous function:
onclick = function() {
copyToClipboard(document.getElementById("a").value);
};
All praise the power of javascript to mislead developers into diagnosing their problems incorrectly!
This is not how you define an inline onclick handler. An inline onclick handler is an attribute(or property, as we'll find out in a bit) of an html element:
<textarea id="a" autofocus="true" onclick="copyToClipboard(this.textContent)"></textarea>
What you did with the <script> tag was simply include some javascript code, to be executed as the browser is parsing your html:
<script> onclick=copyToClipboard(document.getElementById("a").value);</script> calls your function, and assigns its return value to onclick.
But wait, why does your second snippet work?
This is because onclick is also a property of dom elements. It also happens that you can assign a click handler to window itself - this is what your second snippet is actually doing(thanks to an uncool feature of javascript that attempts to assign to an undefined variable assigns to properties of the global object). That means that no matter where you click, your new click handler will be called.
As to your opening question, you can't really say that tags are like includes - a script can involve more than just declarations and definitions, unlike an included file. You can look into some of the module standards/frameworks, like RequireJS, for more similar functionality.

Cant get javascript DOM selectors to work [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does jQuery or a DOM method such as `getElementById` not find the element?
I've been trying to learn js, but im having trouble getting a very simple example to work and i cant seem to find what im doing wrong. From all i understand the below example should work. When i click on the second button, it calls the function f2 and outputs "batman" as an alert, so i know the javascript page is linked correctly. But when i click on the first button nothing happens.
HTML:
<head>
<script type="text/javascript" src="Positioning and flow tests.js"></script>
</head>
<body>
<p id="par1">Test</p>
<button onclick="f1()">Click me for par 1 content</button>
<button onclick="f2()">Click me for predefined text</button>
</body>
</html>
Javascript
// JavaScript Document
var var1 = document.getElementById("par1");
function f1()
{
alert(var1.innerHTML);
}
function f2()
{
alert("batman");
}
You have to put the JavaScript at the bottom of the page, otherwise the par1 element won't be available when your code runs:
<head>
<title>Positioning and flow tests</title>
</head>
<body>
<p id="par1">Test</p>
<button onclick="f1()">Click me for par 1 content</button>
<button onclick="f2()">Click me for predefined text</button>
<script type="text/javascript" src="Positioning and flow tests.js"></script>
</body>
An alternative to this, is to set your code to run when the page has finished loading:
var var1;
window.onload = function () {
var1 = document.getElementById("par1");
};
function f1()
{
alert(var1.innerHTML);
}
function f2()
{
alert("batman");
}
but this will wait until the page has completely loaded, which includes downloading all the images. If you were to click on the first button before all the images have been fully downloaded, you'd get an error.
You need to either put the code after the element or do this:
HTML:
<body onload="init()">
...
JS:
var var1;
function init() {
var1 = document.getElementById("par1");
}
function f1()
{
alert(var1.innerHTML);
}
The problem is you are trying to get an element that has yet to be created and therefore doesn't exist. Using an 'init' function will wait until the entire document has loaded before trying to get the elements.

Categories

Resources