I want to get run a function when I press the w key, I found some solutions but was not able to figure our where to place that code. Also I want it to be executed no matter when I press w as long as I'm on the same web page.
Here is my code:
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<input type="text" onkeydown="keyPressed()">
</head>
<body>
<div id="screen">
</div>
</body>
<script src="main.js"></script>
</html>
Javascript
function keyPressed() {
// this doesn't run.
}
If I made a mistake then please tell me it and if I didn't make a mistake why doesn't it work?
If I understand correctly you want to "listen" for a keydown event and specifically listen for w.
Below is code that does this without an input.
You will have to click in the window to make it work (on a web page it should work without needing to click in the window.)
function ready(callbackFunction){
if(document.readyState != 'loading')
callbackFunction(ev)
else
document.addEventListener("DOMContentLoaded", callbackFunction)
}
ready(ev => {
console.log('DOM is ready.');
// code above checks that the DOM is loaded and ready
// addEventListener on the window and listen for keydown
window.addEventListener("keydown", function(e) {
// Next 4 lines listen for the key and print it to the screen, not really needed.
let str = "KeyboardEvent: key='" + event.key + "' | code='" + event.code + "'";
let el = document.createElement("span");
el.innerHTML = str + "<br/>";
document.getElementById("screen").appendChild(el);
// this listens for w, add your function in here.
if (event.key == "w") {
alert('You pressed lowercase w');
}
}, true);
})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Project</title>
</head>
<body>
<main>
Click in this window to make active. <br>
Then keydown and the key & keycode will show. <br>
keydown lowercase w and it will alert.
<div id="screen"> </div>
</main>
</body>
</html>
Related
I wrote javascript codes.
By clicking the button, the child window pops up and displays a text sent from the parent window using a postMessage function.
My code could sent a text to the child window, but there's no text displayed.
The text is displayed only when I keep clicking the button. I don't want the text to disappear.
I think my code is overridden by a blank script or something, though I don't write any other codes except for below.
Do you have any solution for this?
the parent window html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Parent Window</title>
</head>
<body>
<input type="button" value="TEST_BUTTON" id="testButton">
<script>
var testButton = document.getElementById('testButton');
testButton.addEventListener('click', function(event) {
event.preventDefault();
var newWindow = window.open('./child_window.html', 'popupWindow', 'width=400,height=300');
newWindow.postMessage('this is a content from the parent window.', '*');
return false;
},false);
</script>
</body>
</html>
the child window html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Pop Up Window</title>
</head>
<body>
<h1 id="mainText"></h1>
<script type="text/javascript">
var mainText = document.getElementById('mainText');
window.addEventListener('message', function(event) {
console.log(event.data);
this.mainText.innerText = event.data;
}, false)
</script>
</body>
</html>
I ended this up using localStorage instead.
I have been working an a auto-completion feature for a project that I am working on.
I want the user to be able to click on on of the auto-completions which will query more information about the product.
When assigning a onclick event to that dynamic created DOM element said onclick event automatically triggers.
Now I have reproduced this "error" in a js fiddle:
https://jsfiddle.net/50y4ma8h/2/
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<div id="results">
</div>
</body>
</html>
JS
var resultsElement = document.getElementById("results");
var div = document.createElement("DIV");
div.append("Hey");
div.onclick = querySomething();
resultsElement.innerHTML = div.outerHTML;
function querySomething() {
alert("hey");
}
I do not understand why the function that is assigned to the oncllick event is automatically called.
I would appreciate any Help :)
div.onclick = querySomething();
Is assigning the result of querySomething function to the handler, and not the function itself.
You probably meant:
div.onclick = querySomething;
Also note that moving the innerHTML somewhere else will not bring the bound onclick listener with it, so resultsElement will not have this event attached.
As you don't really append the created div to the resultsElement you can't attach eventListener to it, I change your code a bit.
var resultsElement = document.getElementById("results");
var div = document.createElement("DIV");
div.append("Hey");
div.addEventListener('click', querySomething);
resultsElement.appendChild(div);
function querySomething() {
alert("hey");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<div id="results">
</div>
</body>
</html>
The Html/JS(vanilla) script below ,gives the following error [when used with both an internal script aswell as an external JS file (using the "defer" keyword)] -
How could this error be resolved?
Chrome
Uncaught TypeError: Cannot read property 'onclick' of null
Firefox
TypeError: document.getElementById(...) is null
//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).
document.getElementById("change1").onclick(function(){
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change1 btn pressed");
}
)
document.querySelector("change2").addeventlistener("click",()=>{
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
},false
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<<device-width>>, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event2</title>
<script src= "testJS_event2.js" defer ></script>
</head>
<body>
<div>
<p id="tx1">tx1 <--- this element is null </p>
<h1 id="tx2">tx2 <--- this element is also null </h1><br>
<button id = "change1">Change1</button>
<button id = "change2">Change2</button>
</div>
</body>
</html>
You need to assign function to the onclick event attribute of the element
For querySelector you need to access the element with a # as you are accessing the element with its id
There was a typo for addEventListener
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<<device-width>>, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event2</title>
<script defer="defer">
window.onload = function() {
//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).
document.getElementById("change1").onclick = function() {
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change2 btn pressed");
};
document.querySelector("#change2").addEventListener("click", () => {
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
}, false);
}
</script>
</head>
<body>
<div>
<p id="tx1">tx1
<!--- this element is null-->
</p>
<h1 id="tx2">tx2
<!--- this element is also null -->
</h1>
<br>
<button id="change1">Change1</button>
<button id="change2">Change2</button>
</div>
</body>
</html>
Though defer is used and document is parsed, the defer script will fire before DOMContentLoaded, hence the error.
This Boolean attribute is set to indicate to a browser that the script
is meant to be executed after the document has been parsed, but before
firing DOMContentLoaded.
Scripts with the defer attribute will prevent the DOMContentLoaded
event from firing until the script has loaded and finished evaluating.
Your problem is that the Javascript is executed before you page is fully load, so it can find your elements.
Use window.onload() and it will be good !
Or you can put your <script src= "testJS_event2.js" defer ></script> at the end of your body (better solution for loading time)
You have typo in your code, addEventListener not addeventlistener.
getElementById returns HTMLElement or undefined. HTMLElement does not have onclick property, You need to bind a click event listener to it.
Lastly, you can only query the DOM once it is fully loaded. You JS execute before the code DOM is loaded. That is why the DOM elements your are querying are null/undefined.
You can also bind the onlick event in your butto directly. Here is a working sample code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Event2</title>
<script src="testJS_event2.js"></script>
</head>
<body>
<div>
<p id="tx1">tx1 <--- this element is null </p>
<h1 id="tx2">tx2 <--- this element is also null </h1> <br>
<button id="change1">Change1</button>
<button id="change2">Change2</button>
<button onclick="change3()">Change3</button>
</div>
</body>
</html>
window.onload = function() {
document.getElementById("change1").addEventListener("click", function() {
document.getElementById("tx1").innerHTML = "tx1 changed with JS";
console.log("Change1 btn pressed");
});
document.querySelector("#change2").addEventListener("click", function() {
document.getElementById("tx2").innerHTML = "tx2 changed with JS";
console.log("Change2 btn pressed");
});
};
function change3() {
console.log("Change 3 clicked .......");
}
I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>
This code runs immediately once the page is loaded. The onclick event is completely ignored by javascript. What is an easy fix for this because like youtube when you play a video the document.title is updated with a speaker. I want to learn to do that with external javascript because I can do it with internal javascript in the html.
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="animationcss.css">
</head>
<body>
<script src="animation.js"></script>
<input id="changeButton" type="button" value="Change" ></input>
/External Javascript/
var element = document.getElementById("changeButton");
element.onclick = textChange("changetothis");
function textChange(text){
document.title = text;
}
try calling the function after the document is loaded by placing the script tag below the object or making $(document).ready() function,
this code works fine with me
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
</head>
<body>
<input id="changeButton" type="button" value="Change" ></input>
<script src="script.js"></script>
<body>
</html>
and the script is
var el = document.getElementById("changeButton");
el.onclick = function(){
textChange("changetothis");
}
function textChange(text){
document.title = text;
}
You can achieve your desired effect by using an anonymous function, like so:
document.getElementById("changeButton").onclick = function () {
document.title = newTitle;
}
The variable 'newTitle' should be declared & initalized above this code somewhere in order for it to work.