Why doesn't this code display the button after I hide it? - javascript

When I run this JavaScript code, button2 doesn't get displayed again. I'm not sure why this is happening. I am trying to use this in a game I am creating. I searched this up on Google multiple times and couldn't find an answer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2"></button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "auto";
}
</script>
</html>

A good way to handle this and provide more reusable code is to use <element>.classList.remove() and <element>.classList.add() to set or unset a hidden class. This can also be useful for toggling with <element>.classList.toggle().
This has the added advantage of being able to set your default display style in the CSS rather than burying it in the javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
/* allows setting preferred display in CSS */
display: block;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn1" onclick="toggleBtn2()">
Toggle Button 2
</button>
<button class="btn2 hidden" id="btn2">Button 2</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.classList.remove("hidden");
}
function toggleBtn2() {
btn2.classList.toggle("hidden");
}
</script>
</html>

There is no auto display is CSS. As tarkh mentioned in his answer, display block would insert the new button below the initial button, and other display options would have other behaviors. But the display property does not have a value auto.
This may be my opinion, but I think modern websites shouldn't use the onclick function for events. We should separate our HTML, JS and CSS. This helps with reusability. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
So I would create a solution that uses an event handler in the Javascript. Something like:
window.onload = function(){
const btn2 = document.getElementById("btn2");
const btn1 = document.getElementsByClassName("btn1");
for(let i = 0; i < btn1.length; i++) {
btn1[i].addEventListener('click', function(){
btn2.style.display = "block";
})
}
}

Maybe btn2.style.display = "block";?
Or, as #charlietfl added, btn2.style.display = "inline"; since that is what browser default is for a button
display: block means that the element is displayed as a block, as
paragraphs and headers have always been. A block has some whitespace
above and below it and tolerates no HTML elements next to it, except
when ordered otherwise (by adding a float declaration to another
element, for instance).
display: inline means that the element is displayed inline, inside the
current block on the same line. Only when it's between two blocks does
the element form an 'anonymous block', that however has the smallest
possible width.
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">new button here</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "block";
}
</script>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">Button 2</button>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "inline";
}
</script>
</body>
</html>
Use display = inline or block instead of auto.
Add some text content to button 2 like this:
<button class="btn2" id="btn2">Button 2</button>

CSS: "display: auto;"?
display does not have an auto attribute.
you can try "inline" or "block".
'''
function showBtn2() {
btn2.style.display = "inline";
}
'''

Try using
btn2.style.display = "block";
for your script because css display doesn't have that kind of attribute you
you can read it more here : more
you'll see there's no such thing as display:auto

Related

JavaScript background color change function does not interact with the html button

this is my first time using StackOverflow, so I still don't know how to use the code snippets properly.
I am still a beginner into programming and chose to start with the front-end side, i've done an orange background with "this is the red heading" written in red, it worked.
however, I'm trying to make a button that when it's clicked, only the background color changes from orange to yellow, but the button doesn't do anything at all.
here's the code("estilo" is the name of the CSS file and "responsividade" is the name of the JS file):
function changeColor() {
document.getElementById("redhead").style.backgroundColor = "yellowbg";
}
#redhead {
background-color: orange;
color: red;
padding: 40px;
text-align: center;
}
#yellowbg {
background-color: yellow;
padding: 40px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<body>
<link rel="stylesheet" href="estilo.css">
<script src="responsividade.js"></script>
<h1 id="redhead">this is the red heading</h1>
<button type="button" onclick="changeColor()">Click Here</button>
</body>
</head>
</html>
Here: document.getElementById("redhead").style.backgroundColor = "yellow"; you are trying to assign a css class name to the backgroun color property.
function changeColor() {
document.getElementById("redhead").style.backgroundColor = "yellow";
}
#redhead {
background-color: orange;
color: red;
padding: 40px;
text-align: center;
}
#yellowbg {
background-color: yellow;
padding: 40px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<link rel="stylesheet" href="estilo.css">
<script src="responsividade.js"></script>
<h1 id="redhead">this is the red heading</h1>
<button type="button" onclick="changeColor()">Click Here</button>
</body>
</html>
if you want to change color try document.getElementById("redhead").style.backgroundColor = "yellow";
or if you want to set another id try
document.getElementById("redhead").setAttribute('id', 'yellowbg');
You have written your code in the head tag.
In background-color value given as yellowbg.
function changeColor() {
document.getElementById("redhead").style.backgroundColor = "yellow";
}
#redhead {
background-color: orange;
color: red;
padding: 40px;
text-align: center;
}
#yellowbg {
background-color: yellow;
padding: 40px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<link rel="stylesheet" href="estilo.css">
<script src="responsividade.js"></script>
<h1 id="redhead">this is the red heading</h1>
<button type="button" onclick="changeColor()">Click Here</button>
</body>
</html>
#yellowbg ruleset all properties are there in #readhead ruleset except background-color so in js, you can just update background color only.
const colorChanger = {
'eq' : 0,
'change' : function(targetID, colorCircles) {
document.getElementById(targetID).style.backgroundColor = colorCircles[this.eq];
this.eq = (this.eq === colorCircles.length-1) ? 0:this.eq += 1;
}
}
#test{
border :1px solid #000;
width :100px;
height :100px;
}
<div id="test"></div>
<button onclick="colorChanger.change('test', ['red','yellow', 'green', 'blue', 'purple'])">Change Color</button>
<!--
colorChanger.change('test', ['red','yellow', 'green', 'blue', 'purple']
------------------------------------------------------
>target is something with id 'test'
>and background color of target ID will be change using this circles ['red','yellow', 'green', 'blue', 'purple']
-->
In your Js function you need to a background color as you trying to do.
document.getElementById("redhead").style.backgroundColor = "yellowbg";
"yellowbg" is not a color but an Id.
So you need to change that to
document.getElementById("redhead").style.backgroundColor = "yellow";
You can add css property to a class of an element and with js change the class name to add different property to that element.
document.getElementById("redhead").className = "newClass";

Change form values using JavaScript

I have been asked to change text and style of a specific button within a form after a submit.
JavaScript
openWarningBox(
"/URL",
[{
'classNames':'button sec',
'text':'Continue',
'clickEvent': function() {
$(document.forms.button).trigger('submit');
}
}]
);
HTML
<form name="button" onsubmit="location.href='/URL'; return false;"></form>
I am aware this is done in a weird/wrong way and if it was written properly it would not have been an issue, but is there some way for me to change that button's classNames and text after it is being submitted?
I am not sure if this is what you are looking for but I used the DOM to change the button text and style you can also change the font that way. The DOM seems like a good option to accomplish this task.
var btn = document.getElementById('btn')
btn.addEventListener('click', change)
function change(e){
e.preventDefault()
btn.style.backgroundColor = 'blue';
btn.style.border = 'blue';
btn.style.colr = 'black';
btn.style.borderRadius = '26px';
btn.innerHTML = 'Submitted'
}
button{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button type="submit" id='btn'>Submit</button>
</body>
</html>

Dark mode switch using HTML5 and CSS

I have this simple code to turn a webpage into dark/light mode. It works fine on the page you are, but if I click any links or buttons to redirect me from index.html to test.html for example, then the settings resets to default. Let's say I want to browse my page in light mode, and lick test button it goes back to dark mode.
How do I make it remember to stay in the same mode I choose? Here is what I got.
Index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Dark -Light Mode Switcher</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<body id="body" class="dark-mode">
<h1>Dark/Light Mode Switcher</h1>
<button type="button" name="dark_light" onclick="toggleDarkLight()" title="Toggle dark/light mode">🌛
</button>
<p><button name="test">TEST PAGE</font></button>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
Script.js
function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}
Style.css
body.dark-mode {
background-color: #111;
color: #eee;
}
body.dark-mode a {
color: #111;
}
body.dark-mode button {
background-color: #eee;
color: #111;
}
body.light-mode {
background-color: #eee;
color: #111;
}
body.light-mode a {
color: #111;
}
body.light-mode button {
background-color: #111;
color: #eee;
}
If you update your Script.js like below, you will obtain what you want :
body.className=localStorage.getItem("stateMode");
function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
localStorage.setItem("stateMode",body.className);
}

How to have a class toggle function to change and unchange a CSS button styling on click?

I am trying to write a code that toggles the styling of a button. At first, I thought I could do this with CSS and the active selector. But I also want to be able to undo the changes on click, which the active selector does not. Then I thought I might be able to do this with JavaScript and a class toggle function.
Unfortunately, I am not that familiar with JavaScript. I have written a code and it partially works, but it always changes the styling of the same element (maybe because it is the first element with the specific class?).
Is there a way to build a flexible function which can apply to several elements, depending on which one I click on?
function testtoggle() {
if(document.getElementById("testknop").className == "nietactief"){
document.getElementById("testknop").className = "actief";
} else {
document.getElementById("testknop").className = "nietactief";
}
}
button {
cursor: pointer;
padding: 16px;
font-size: 16px;
border-radius: 100%;
}
.nietactief {
background-color: #a8a8a8;
border: 5px solid #ddd;
}
.actief {
background-color: purple;
border: 5px solid green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle()()">1e</button>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle()">2e</button>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle()()">3e</button>
</body>
</html>
You should look into the classList feature in JavaScript. It makes it easy to add, remove and toggle classes on elements.
// Get a list of all the buttons in the group
let buttons = Array.from(document.querySelectorAll('[type=button]'))
// For each button add a click event listener
// This allows us to remove the 'onclick' from the html
buttons.forEach(item => {
item.addEventListener('click', e => {
// When the button is clicked, remove the active state
// Then add the inactive state
buttons.forEach(button => {
// If the current button does not equal the clicked button
// Remove the active state class
button != e.currentTarget && button.classList.remove("actief")
button.classList.add("nietactief")
})
// Toggle the state of the clicked button
item.classList.toggle("actief")
})
})
button {
cursor: pointer;
padding: 16px;
font-size: 16px;
border-radius: 100%;
}
.nietactief {
background-color: #a8a8a8;
border: 5px solid #ddd;
}
.actief {
background-color: purple;
border: 5px solid green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button type="button" id="testknop" class="nietactief">1e</button>
<button type="button" id="testknop" class="nietactief">2e</button>
<button type="button" id="testknop" class="nietactief">3e</button>
</body>
</html>
What you are observing is the expected behavior to the document.getElementById
You could pass a reference to the button triggering the event:
window.testtoggle = function(elmnt) {
if(elmnt.className == "nietactief"){
elmnt.className = "actief";
} else {
elmnt.className = "nietactief";
}
}
button {
cursor: pointer;
padding: 16px;
font-size: 16px;
border-radius: 100%;
}
.nietactief {
background-color: #a8a8a8;
border: 5px solid #ddd;
}
.actief {
background-color: purple;
border: 5px solid green;
}
<button type="button" id="testknop" class="nietactief" onclick="testtoggle(this)">1e</button>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle(this)">2e</button>
<button type="button" id="testknop" class="nietactief" onclick="testtoggle(this)">3e</button>
Alternatively you could consider JQuery to fetch all dom elements matching a specific criteria and update its class:
$("button").attr('class', 'newClass');
or another client framework like vue.js

Removing dynamic divs made with JS on click

My code knowledge is very limited, comes from CodeHS and Codecademy so bear with me.
So I am trying to make a list of numbers, that can be deleted on click. So far so good with the number list, but I still can't figure how to remove them when I click the div box.
I know theres JSFiddle, but I think this is best I could do:
http://www.codecademy.com/rfabrega/codebits/xZ61aJ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
color: #000;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
</style>
</head>
<body>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
you have to create a function on click that deletes the target div tag:
so in your code, after creating the div element. insert this:
divTag.onclick = function(){this.parentNode.removeChild(this)};
$(document).ready(function(){
$('p').hide();
$("body").on("click",".divContainer",function(){
$(this).remove();
});
});

Categories

Resources