Over the recent days 've been trying to make buttons that changes a text's color by using
document.querySelector.('class name').style.color
in a function while using onclick to put that function in the button, but it always says my function *chanageColor isn't defined. Could some of you help me please? It also says theres an unexpected token, please help me with that as well!
<body>
<div class="box">
<h1> Hello</h1>
</div>
<script>
function changeColor(){
document.querySelector.('.box').style.color = 'pink';
}
</script>
<button class="pink">Pink</button>
</body>
</html>
Well, there's nothing in your code here that would even try to call your function so I can't say for sure what your issue is, but to hook up the click event of the button to your function, you use: .addEventListener().
Now, you do have a typo:
document.querySelector.('.box') // <-- The dot before ( is wrong
And your script element should be the last thing before you close the body tag so that by the time the script runs, all the HTML will have been parsed into memory.
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink">Pink</button>
<script>
document.querySelector("button.pink").addEventListener("click", changeColor);
function changeColor(){
document.querySelector('.box').style.color = 'pink';
}
</script>
And while this works, inline styles should be avoided whenever possible because they are the hardest type of CSS styling to override and lead to duplication of code. Instead, use CSS classes whenever you can (almost always) as shown here:
.pinkText { color:pink; }
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink">Pink</button>
<script>
// Get your DOM element references just once, not every time the function runs:
const box = document.querySelector('.box');
document.querySelector("button.pink").addEventListener("click", changeColor);
function changeColor(){
box.classList.add('pinkText');
}
</script>
<!DOCTYPE html>
<html>
<body>
<div class="box">
<h1> Hello</h1>
</div>
<button class="pink" onclick="changeColor()">Pink</button>
</body>
<script>
function changeColor(){
document.querySelector('.box h1').style.color = 'pink';
}
</script>
</html>
Related
<p id="para1">Hi</p>
<button onclick="style()">Submit</button>
<script>
function style(){
var text= document.getElementById("para1").style.color="green";
}
</script>
I added html code using javascript. All the headings and divs are working fine except the Button. The Button is not added or may be not working for some reasons. Please check my code give some suggestions. When I used the same code as html it worked fine.
style has a special meaning in JavaScript, use some other name as the name of your function:
<p id="para1">Hi</p>
<button onclick="elementStyle()">Submit</button>
<script>
function elementStyle(){
document.getElementById("para1").style.color="green";
}
</script>
Another way is to add a class to the element, that should be styled. Then you are very flexible in styling it:
<p id="para1">Hi</p>
<button onclick="stylePara1()">Submit</button>
<style>
.green-text {
color: green
}
</style>
<script>
function stylePara1(){
document.querySelector('#para1').classList.add('green-text');
}
</script>
Or use inline syntax:
<p id="para1">Hi</p>
<button onclick="document.querySelector('#para1').classList.add('green-text')">Submit</button>
<style>
.green-text {
color: green
}
</style>
Is submit a reserved word in Javascript?
Take a look at this code:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="submit()">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
</body>
</html>
I'm trying to understand why I can't call the submit() function inside the <form> tag but it works outside the tag. I think it is a reserved word even because changing the function name the script works well but I can't find any information about that on mdn
I'm not a JS guru, so can someone help me understand this strange behaviour?
The problem is that submit() is a built-in function that gets called whenever a <form> gets submitted. To have custom functionality kick in which a form is submitted, you'll not only need to use a different function name, but also prevent the default form submission with event.preventDefault(), passing the event into the function.
This can be seen in the following -- note that the sayHello() will clear the screen (with an attempted form submission), whereas customSubmit() will not:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function customSubmit(e){
e.preventDefault();
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="customSubmit(event)">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="customSubmit(event)">Submit - outside</button>
</body>
</html>
Buttons inside forms automatically submit the form, as long as the button doesn't have an event handler, or has an event handler that doesn't preventDefault():
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
(see how the form gets submitted - the page in the snippet disappears)
It has nothing to do with the submit function name.
But still, using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener.
Inline handlers should be avoided just as much as eval should be avoided.
If you want to prevent a button inside a form from submitting the form, call e.preventDefault() like this:
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
const [b1, b2] = Array.from(document.querySelectorAll('button'));
b1.addEventListener('click', (e) => {
e.preventDefault();
sayHello();
});
b2.addEventListener('click', (e) => {
e.preventDefault();
submit();
});
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
Pressing a button in a form reloads the page.
<html>
<head>
</head>
<body>
<!--Any button in the form will submit the form and reload the page-->
<form>
<button id="btn1">Say hello</button>
<button id="btn2">Submit</button>
<button>Anything</button>
</form>
<!--these ones don't-->
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
<script>
// notice the page loads when we click the 'anything' button, even without an event handler
//the delay allows you to see it happening
console.log("loading page...");
setTimeout(welcome, 500);
function welcome() {
console.log("page has been loaded");
}
// adding preventDefault to these, stops the form from submitting
function sayHello(e) {
console.log('Hello!');
e.preventDefault();
}
function submit(e) {
console.log('Submit!')
e.preventDefault();
}
//This is how you add event handlers
let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
btn1.addEventListener('click', sayHello);
btn2.addEventListener('click', submit);
</script>
</body>
</html>
This is very frustrating as it seems so simple yet is not working.
In my body I have
<div id ="splashscreen" style="display:block">
<h3>title</h3>
<p>text</p>
<inputtype="button" value="Start" onClick="splash();" />
</div>`
And in my head, within script tags I have
function splash() {
var divSplash = document.getElementById("splashscreen");
divSplash.style.display = "none";
}
Surely when Start button is clicked, the splash() function should be called and the display of my splashscreen div be chanted to none?
The problem here is that the you write language="text/javascript", if you use instead language="javascript" it works.
I recommend you remove the language property and use type="text/javascript" instead. If you're using HTML5, you can omit the type property.
<script type="text/javascript">
function startGame() {
var divSplash = document.getElementById("splash");
divSplash.style.display = "none";
}
</script>
Also, the language property is now obsolete.
Using the exact code that you show here, I get the error 'divSplash is null.' This is to be expected -- your div is named "spashscreen" but your JS function is looking for a div named "splashscreen." (You're missing an 'l').
When I fix the typo, it works.
You're not using the same id :)
spashscreen != splashscreen
Here is the answer in a jsfiddle
HTML:
<div id ="splashscreen" style="display:block">
<h3>title</h3>
<p>text</p>
<button onclick="splash()">Start</button>
</div>
Javascript:
function splash() {
var divSplash = document.getElementById('splashscreen');
divSplash.style.display = "none";
}
I'm testing out localStorage to see if it can be used in my app, but when I try to store data from a text input box to it, the screen goes blank. How can I fix this? Here is the code:
<html>
<head>
<script type="text/javascript">
function write() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display').innerHTML = data;
}
</script>
</head>
<body>
<input id="input" type="text" />
<button type="button" onclick="write()">
Write
</button>
<p id="display">
Display
</p>
<button type="button" onclick="read()">
Read
</button>
</body>
</html>
change your function name from write to something else. it sounds like you are accidentally invoking document.write, which would blank out your entire page.
You cannot use a function called write on the global (document) namespace ... call it something else and it works fine
<input id="input" type="text" />
<button type="button" onclick="somethingelse();">
Write
</button>
<p id="display1">
Display
</p>
<button type="button" onclick="read()">
Read
</button>
function somethingelse() {
localStorage.setItem('item', document.getElementById('input').value);
}
function read() {
var data = localStorage.getItem('item');
document.getElementById('display1').innerHTML = data;
}
Working example here
The code inside html event handlers is ran effectively like:
with(document) {
with(this) {
write();
}
}
so your write is shadowed (it calls document.write). You can simply refer to the correct write with window.write():
<button type="button" onclick="window.write()">
Ultimately it's better not to use inline html events at all. A simple button.onclick = write would have worked, where button is reference to the element.
Here is my code:
<html>
<head>
<title>My Game Title Goes Here!</title>
<script type="text/javascript">
function startGame(){
document.getElementById("2").innerHTML = ('Testing!');
}
document.body.onload = keyListener(){
document.getElementById("1").onkeypress = startGame;
}
</script>
</head>
<body>
<div class="title" name="Game Title" id="0">Game Title</div>
<div tabindex="0" class="gamecontainer" name="Game Container" id="1">
Press any key to start.
</div>
<div class="gamemonitor" name="Game Monitor" id="2">
Game Monitor:
</div>
</body>
</html>
I doesn't work like I expect it to (I'm using Google Chrome).
It only works if I run it directly, like this:
<div tabindex="0" class="gamecontainer" name="Game Container" id="1" onkeypress="document.getElementById('2').innerHTML = ('Testing!')">
Press any key to start.
</div>
<div class="gamemonitor" name="Game Monitor" id="2">
Game Monitor:
</div>
I checked over my code tons of times and i cannot find any clear mistakes like typos or anything. If that is the problem then I am sorry to have wasted your time but this is realy buggin' me.
Element IDs can't start with a number, it's almost definitely contributing to your issue here. Change the IDs in both the HTML and JS to begin with a letter.
Second of all, the keyListener line should probably be something like this:
window.onload = function(){
document.getElementById("newId").onkeypress = startGame;
}
document.body doesn't have an onload property. It should be window.onload instead.
window.onload = function(){
document.getElementById("1").onkeypress = startGame;
}
DEMO: http://jsfiddle.net/9khng/
Change :
document.body.onload = keyListener(){
document.getElementById("1").onkeypress = startGame;
}
To:
document.body.onload = function(){
document.getElementById("1").onkeypress = startGame;
}
And, id shouldn't begin with a number as it's an invalid HTML.
Chrome seems to overcome this mistake, but it shouldn't be used.
And move the code to the the <body> tag or use window.onload
document.body doesn't exist above the <body>.
I think IDs can't start with a number.
Try fixing your "onkeypress" attribute. Your quotes are messed up.
onkeypress="document.getElementById('2').innerHTML = ('Testing!')"