My Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ATM Interfacetest</title>
<link rel="stylesheet" type="text/css" href="css/rahmen/rahmen.css">
<script>
function testwindow(){
var tmp = document.createElement('div');
tmp.id = 'idtest';
tmp.className = 'classtest';
document.getElementById('xbuttonsHeinz-Ulf').appendChild(tmp);
document.getElementById('idtest').addEventListener('click', test(), false);
}
function test(){
alert('Alarm!');
}
</script>
</head>
<body onload="testwindow()">
<div id="xbuttonsHeinz-Ulf" class="xbuttons">
<div id="schließenHeinz-Ulf" class="symbol">x</div>
<div id="minimierenHeinz-Ulf" class="symbol"> - </div>
<div id="maximierenHeinz-Ulf" class="symbol">□</div>
</div>
</body>
</html>
Drives me crazy. Trying to add the Eventlistener makes the test() function to be excuted directly, without waiting to clicked.
Whats my mistake.
I searching for a good idea to dynamically create html tags with option to add eventhandlers.
Trying:
tmp.onclick = test();
also executes the function directly w/o waiting for a click.
Given the expressions
test() - the result of a call to the function test with no
arguments passed.
test - a reference to the function test.
You want the latter. The former calls test as soon as the line is reached. addEventListener(...) wants a reference to an EventListener, not the result of the handled event.
Related
This question already has answers here:
javascript function name cannot set as click?
(6 answers)
Closed 6 months ago.
I have a relatively trivial problem, that has caused me to get stumped for a few hours
I am trying to get my button to call a JavaScript function that logs to console
Here is my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="script.js"></script>
<meta charset="UTF-8">
<title>McKinsey Prep</title>
<div>
<button onclick="click()">Some Button</button>
</div>
</head>
<body>
</body>
</html>
The button here is calling the click() method in this JavaScript file
console.log("Code has reached here")
function click(){
console.log("Button was clicked REEEEe")
}
The script.js file only has this function, I DO NOT want to execute code in my HTML document
When I run my index.js it prints the first print statement but the console.log in the function call does not appear on console when I click my button
NOTE
I am left clicking my index.html and pressing run to run my code.
What could be the issue?
Click() is a reserved name, you can't use it on a function because there is a native method on JS with that name.
Change the name of your function and try again.
Here is an example
<button onclick="clicked()">Some Button</button>
function clicked(){
console.log("Button was clicked REEEEe")}
The name of the function, click, is the issue. click is not a reserved word in JavaScript but the name does exist elsewhere in the scope where the onclick handler runs. You have 2 options:
Change the function name (doClick, for example).
Qualify the function name by referring to it as window.click in the onclick handler: onclick="window.click()"
There's a much more in-depth explanation here: javascript function name cannot set as click?
Unrelated to this, but something that could confuse someone during debugging: In your example code, your <div> is inside the <head> part of the HTML page. That content should actually be in the <body> section below, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="script.js"></script>
<meta charset="UTF-8">
<title>McKinsey Prep</title>
</head>
<body>
<div>
<button onclick="doClick()">Some Button</button>
</div>
</body>
</html>
As you can see below, I have a function,createCharacter(), that calls another function, getUserInput(). This function is intended to grab the value of a text input element and return that value to be stored in the "name" variable within the createCharacter. However, if you run this code. It completely runs through both functions, never giving the opportunity for the user to input a value. Perhaps a more specific question is, how can I make this function wait for the variable to be defined before returning it to createCharacter? I've tried to wrap the code in a while loop that will run for as long as value is undefined. Didn't work, created an infinite loop and crashed. ANY solution to this problem will be greatly appreciated. I feel like the solution is so simple, but I just can't figure it out for the life of me. Thanks.
var messageDisplay = document.querySelector(".message-display");
var menuInput = document.querySelector(".menu-input");
var playerInput = document.querySelector(".player-text")
function createCharacter() {
messageDisplay.textContent = "Welcome! What is your name?";
var name = getUserInput();
messageDisplay.textContent = "Hello " + name + "!";
}
function getUserInput() {
var textValue = playerInput.value;
return textValue;
}
createCharacter();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<form class="menu-input-content">
<input class="player-text" type="text">
<input class="submit-button" type="submit">
</form>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I think you have a misunderstanding of how the DOM and the user interact. The DOM is event based. You can start by add an change event listener to your input element (or on the submit button):
menuInput.onchange = createCharacter;
And then remove the call to createCharacter, the last line in the code you posted.
This will then call the createCharacter() method when you change the text in the input at all, which is probably not what you want. You could also try:
var menuSubmit = document.querySelector(".submit-button");
menuSubmit.onclick = createCharacter;
And that is probably more on the right track.
However, given your misunderstanding in the first place, perhaps you need to reconsider how you approach your design?
The reason it runs through the code immediately is because of the last line. The browser loads the JS and executes everything in the global scope. Your query selectors are run and stored in those variables, the functions defined, and then on the last line you call one of the defined functions.
To fix this you need to redesign your app to be event based. Keep defining needed variables and functions in the global scope, as you are doing here, but then change your execution to be in response to events.
I think you are looking for something like this. You should be using the events to get what you wanted. You are executing createCharacter() before even the user clicked the Submit button. Hence you see "Hello !" as there is no user input initially.
function submitClicked(event) {
var messageDisplay = document.querySelector(".message-display");
var playerInput = document.querySelector(".player-text");
messageDisplay.innerHTML = "Hello " + playerInput.value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<input class="player-text" type="text">
<input class="submit-button" onclick="submitClicked()" type="submit">
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I have a page that references an external javascript file, and when I tell it run a function onload, it is giving me errors (I assume because it is firing before the page is loaded.) "Cannot set property 'innerHTML' of null"
What do I need to do here to fire run() after the page is loaded?
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
JS
window.onload = run();
function run() {
document.getElementById("test").innerHTML = "found it";
}
It should be:
window.onload = run;
When you do:
window.onload = run();
You're actually running the function called run, and then assigning its return-value (undefined in this case) to window.onload.
This function is running before the page even gets loaded (since you are running it explictly by doing run()), at which time the div with id test doesn't even exist. This is why you're getting the error.
Try this instead:
window.onload = run
When you do window.onload = run() you are immediately executing run() and assign whatever is returned to the window.onload property. This is why it’s not working correctly.
I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?
I have created a JSFiddle to describe the issue. Why isn't the alert displayed when I call the doSomething() function?
You need to disable framework option in jsfiddle for javascript to work
DEMO
function doSomething() {
alert('Hello!');
}
This is because doSomething() function is not defined in the HTML page. In jsfiddle your function (in js pane) is wrapped by document onload event of jquery. (see at the left side of jsfiddle for settings). So Its executed like this,
$(document).ready(function() {
function doSomething() {
alert('Hello!');
}
});
See how its wrapped. Its not accessible. To fix it you should assign it to window object.
In the js pane write the function as
window.doSomething=function() {
alert('Hello!');
}
It'll work
Its recommended you do not use onclick attributes of an HTML elements. Its better to assign event handler with JS.
$("img").click(function(){
alert("Hello");
});
This is a "fiddle-thing". Pick nowrap (head) from the first selection in the "Choose Framework" field.
What JsFiddle does for you is creating the <HTML>, <head> and <body> tags for you. You shouldn't include them in your HTML, because that would make the markup invalid after JsFiddle processed it. It also wraps your JS in the document's onload event. So your function was not defined in the root scope as you thought, but in th scope of the document.onload function, and you couldn't reach it from within the body, because that is outside of that function. I changed the JsFiddle attribute 'wrap in' to 'no wrap (head)' and it worked.
Your function dosomeThing() is not defined in the page
just replace header tag with this one
<head>
<script>
function doSomething() {
alert('Hello!');
}
</script>
</head>
and then try again
Here is your complete code. just copy and paste your editor. it is
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Javascript Events</title>
<script type='text/javascript'>
window.onload = function() {
var image_one = document.getElementById('imageOne');
var image_two = document.getElementById('imageTwo');
image_one.onclick = function() {
alert('Hello!');
}
image_two.onclick = function() {
alert('Hello!');
}
}
</script>
</head>
<body>
<img id="imageOne" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG" />
<img id="imageTwo" src="http://upload.wikimedia.org/wikipedia/en/7/70/Example.png" />
</body>
</html>