button toggle display show hide - javascript

I want to show-hide the display of these layers with a button click. I can't figure out how to do it with 2 buttons, and 2 divs...
Html:
<div id="first">This is the FIRST div</div>
<div id="second">This is the SECOND div</div>
<button id="toggle">Show first div and hide second div</button>
<button id="toggletoo">Show second div and hide first div</button>
Css:
#first {
display: none;
}
#second {
display: none;
}
Js:
const targetDiv = document.getElementById("first");
const btn = document.getElementById("toggle");
btn.onclick = function () {
if (targetDiv.style.display !== "none") {
targetDiv.style.display = "block";
} else {
targetDiv.style.display = "none";
}
}
https://codepen.io/MaaikeNij/pen/YzrgbQw

Try with the following code:
#first{
display: block; /* <--- change */
}
#second {
display: none;
}
const firstDiv = document.getElementById("first");
const secondDiv = document.getElementById("second");
document.getElementById("toggle").onclick = function () {
if (firstDiv.style.display === "none") {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
} else {
firstDiv.style.display = "none";
secondDiv.style.display = "block";
}
}

There's lots of ways to do this. One common way I've seen in various templates is to add and remove classes. Another way is to call the function from the button's onclick attribute. But my favorite is to write a function that requires no editing of the div HTML because I don't want to interfere with the HTML guy's work, I just want to put functioning code in there. (BTW, I am positive there is a more elegant way to write this, but here ya go!)
const firstDiv = document.querySelector("#first");
const secondDiv = document.querySelector("#second");
const firstButt = document.querySelector("#toggle");
const secondButt = document.querySelector("#toggletoo");
firstButt.addEventListener("click",toggleDivShowHide);
secondButt.addEventListener("click",toggleDivShowHide);
function toggleDivShowHide() {
if (firstDiv.style.display !== "none") {
firstDiv.style.display = "none";
secondDiv.style.display = "block";
} else {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
}
}
You're saying "if the first div is set to none, then set it to block and set the second div to none. Otherwise, do the opposite."

I tried something different, this is working :)))
<div id="first" style="display:none;"> This is the FIRST div</div>
<div id="second" style="display:none;"> This is the SECONDdiv</div>
<input type="button" name="answer" value="Show first div and hide second div" onclick="showDivOne()" />
<input type="button" name="answer" value="Show second div and hide first div" onclick="showDivTwo()" />
function showDivOne() {
document.getElementById('first').style.display = "block";
document.getElementById('second').style.display = "none";
}
function showDivTwo() {
document.getElementById('second').style.display = "block";
document.getElementById('first').style.display = "none";
}
https://codepen.io/MaaikeNij/pen/vYeMGyN

Correction: you should add event Listener for both toggle & toggletoo.
Solution: solution with reusable code.
const Toggles = document.querySelectorAll('.toggle');
const Hides = document.querySelectorAll('.hide');
Toggles.forEach((el) => {
el.addEventListener("click", (e) => {
Hides.forEach((el) => {
el.parentElement.firstElementChild.classList.add('hide');
});
e.target.parentElement.firstElementChild.classList.toggle('hide');
});
})
.hide {
display: none;
}
<div>
<div class="hide">This is the FIRST div</div>
<button class="toggle">Show first div and hide first div</button>
</div>
<div>
<div class="hide">This is the SECOND div</div>
<button class="toggle">Show second div and hide first div</button>
</div>
<div>
<div class="hide">This is the Third div</div>
<button class="toggle">Show Third div and hide first div</button>
</div>
<div>
<div class="hide">This is the Fourth div</div>
<button class="toggle">Show Fourth div and hide first div</button>
</div>

For precisely such cases, javascript has the toggle function. I rewrite your code a little bit.
const btns = document.querySelectorAll(".toggleBtn");
btns.forEach(b => {
b.onclick = function (e) {
reset();
console.log(e.target.getAttribute('data-target'))
const target = e.target.getAttribute('data-target');
const t = document.querySelector('#' + target);
t.classList.toggle('hide');
}
});
function reset() {
const divs = document.querySelectorAll('.out');
divs.forEach(d => d.classList.add('hide'))
}
.hide {
display: none;
}
<div id="first" class="out hide">This is the FIRST div</div>
<div id="second" class="out hide">This is the SECOND div</div>
<button class="toggleBtn" data-target="first">Show first div and hide second div</button>
<button class="toggleBtn" data-target="second">Show second div and hide first div</button>

Related

Why does toggling visibility works only after second click?

I have a button that should toggle between visibility visible and hidden, and even though I specify in CSS that the div has visibility: hidden, the JS code first sees the CSS as blank (as if I did not specify the style).
Only after the second click (mouseup event in my case), it detects the visibility and the toggling starts working, why?
Here's a snippet:
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
if (div.style.visibility === "hidden") {
div.style.visibility = "visible";
} else {
div.style.visibility = "hidden";
}
}
#div {
visibility: hidden;
}
<button id="button"> toggle </button>
<div id="div">
<h1> Hello, World! </h1>
</div>
div.style reads from the style attribute not the actual applied styles. To fix this you can either use inline styling or get the computed style via getComputedStyle().
Example inline styling:
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
if (div.style.visibility === "hidden") {
div.style.visibility = "visible";
} else {
div.style.visibility = "hidden";
}
}
<button id="button"> toggle </button>
<div id="div" style="visibility: hidden;">
<h1> Hello, World! </h1>
</div>
Example getComputedStyle():
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
const style = window.getComputedStyle(div);
if (style.visibility === "hidden") {
div.style.visibility = "visible";
} else {
div.style.visibility = "hidden";
}
}
#div {
visibility: hidden;
}
<button id="button"> toggle </button>
<div id="div">
<h1> Hello, World! </h1>
</div>
EDIT: As pointed out in the comments toggling a class is another alternative. This is especially useful if you need to change more then one style.
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
div.classList.toggle('show');
}
#div {
visibility: hidden;
}
#div.show {
visibility: visible;
}
<button id="button"> toggle </button>
<div id="div">
<h1> Hello, World! </h1>
</div>
To evaluate style properties of an element, you need to use the window.getComputedStyle() method.
In your case, the code should be:
<!DOCTYPE html>
<html>
<style>
#div {
visibility: hidden;
}
</style>
<body>
<button id="button"> toggle </button>
<div id="div">
<h1> Hello, World! </h1>
</div>
<script>
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
 if(window.getComputedStyle(div).visibility === "hidden") {
div.style.visibility = "visible";
} else {
div.style.visibility = "hidden";
}
}
</script>
</body>
</html>
Soi if you don't want to use inline-css;
let button = document.querySelector("#button");
button.addEventListener("mouseup", toggleVisibility)
function toggleVisibility() {
let div = document.getElementById("div");
let compStylesStatus = window.getComputedStyle(div).getPropertyValue('visibility');
if (compStylesStatus === "hidden") {
div.style.visibility = "visible";
} else {
div.style.visibility = "hidden"
}
}
#div {
visibility: hidden;
}
<button id="button"> toggle </button>
<div id="div">
<h1> Hello, World! </h1>
</div>

Changing class of button and display of div with JavaScript

I have JavaScript to show/hide div on click. Inside that div are more buttons to show/hide PNGs.
I want the clicked button to have a bottom border line until another button in that div is clicked.
I have achieved this but each time I click on a button in the shown div the bottom border line stays on the button when I click the next button.
I've spent hours trying to fix this. please help
let wildCard = document.querySelectorAll(".element-select-container button");
for (let button of wildCard) {
button.addEventListener('click', (e) => {
const et = e.target;
const active = document.querySelector(".active");
let redline = (".redline");
if (active) {
active.classList.remove("redline");
active.classList.remove("active");
}
et.classList.add("active");
et.classList.add("redline");
let allContent = document.querySelectorAll('.button-wrapper');
for (let content of allContent) {
if(content.getAttribute('data-e') === button.getAttribute('data-e')) {
content.style.display = "block";
}
else {
content.style.display = "none";
}
}
});
}
HTML
<div class="element-select-container">
<button id="but81" class="but81 redline" data-e="81" type="button" name="">Doors</button>
<button id="but82" class="but82" data-e="82" type="button" name="">Windows</button>
<button id="but83" class="but83" data-e="83" type="button" name="">Facia</button>
<button id="but84" class="but84" data-e="84" type="button" name="">Guttering</button>
<button id="but85" class="but85" data-e="85" type="button" name="">Garage</button>
<button id="but86" class="but86" data-e="86" type="button" name="">Steps</button>
</div>
CSS
.redline {
border-bottom: 2px solid red;
}
The issue is, on first load, the first button is redline but not active - so, when you press a different button, the code to remove redline from active doesn't find active so redline isn't removed
simple fix
const active = document.querySelector(".active,.redline");
As follows
let wildCard = document.querySelectorAll(".element-select-container button");
for (let button of wildCard) {
button.addEventListener('click', (e) => {
const et = e.target;
const active = document.querySelector(".active,.redline");
if (active) {
active.classList.remove("redline");
active.classList.remove("active");
}
et.classList.add("active");
et.classList.add("redline");
let allContent = document.querySelectorAll('.button-wrapper');
for (let content of allContent) {
if(content.getAttribute('data-e') === button.getAttribute('data-e')) {
content.style.display = "block";
}
else {
content.style.display = "none";
}
}
});
}
.redline {
border-bottom: 2px solid red;
}
<div class="element-select-container">
<button id="but81" class="but81 redline" data-e="81" type="button" name="">Doors</button>
<button id="but82" class="but82" data-e="82" type="button" name="">Windows</button>
<button id="but83" class="but83" data-e="83" type="button" name="">Facia</button>
<button id="but84" class="but84" data-e="84" type="button" name="">Guttering</button>
<button id="but85" class="but85" data-e="85" type="button" name="">Garage</button>
<button id="but86" class="but86" data-e="86" type="button" name="">Steps</button>
</div>

I want to make a stepper component

I want to hide prev btn and the other words
But I want to show them and prev btn one by one when I press next button and display finish btn i am on the latest word.
The buttons, prev, next and finish do the things which are not the same when I have finish button I want to post the words.
I tried many time but not worked. Here is my code that I've tried:
function nextBtn() {
var itemOne = document.getElementById("step-1");
var itemTwo = document.getElementById("step-2");
var itemThree = document.getElementById("step-3");
var itemFour = document.getElementById("step-4");
var prevBtn = document.getElementById("prevBtn");
var nextBtn = document.getElementById("nextBtn");
if (itemOne.style.display == "block" && itemTwo.style.display == "none" && prevBtn.style.display == "none") {
itemOne.style.display = "none";
itemTwo.style.display = "block";
prevBtn.style.display = "block";
}
else {
console.log('Xatolik ishlamayapti');
}
}
#step-1 {
display: block;
}
#step-2 {
display: none;
}
#step-3 {
display: none;
}
#step-4 {
display: none;
}
#prevBtn {
display: none;
}
#nextBtn {
display: block;
}
<div class="step-container">
<div id="step-1">Hello</div>
<div id="step-2">Hi</div>
<div id="step-3">Salom</div>
<div id="step-4">Molas</div>
<button id="prevBtn" #click="prevBtn()">back</button>
<button id="nextBtn" #click="nextBtn()">next</button>
</div>
What's wrong at above link.
Thank you in advance.
The main problem with your approach is that itemOne.style.display == "block" will not evaluate to true because it doesn't consider that the node has some css set externally.
It would make more sense to use html classes for your step divs so that you can select them all at once with querySelectorAll().
The logic would be easier to manage if you use a variable to track which number step is the current step.
Then you can just increase and decrease the variable each time you click on either the previous or next buttons.
const allSteps = document.querySelectorAll('.step')
const totalSteps = allSteps.length
const prevButton = document.querySelector('#prevBtn')
const nextButton = document.querySelector('#nextBtn')
const finishButton = document.querySelector('#finishBtn')
// Hide everything except for #step-1
document
.querySelectorAll(".step:not(#step-1)")
.forEach(step => (step.style.display = "none"))
// Hide the prev button
prevButton.style.display = 'none'
// Hide the finish button
finishButton.style.display = 'none'
let currentStep = 1
function nextBtn() {
currentStep++;
refreshDisplay()
}
function prevBtn() {
currentStep--;
refreshDisplay()
}
function refreshDisplay() {
// hide every step
allSteps.forEach(step => (step.style.display = "none"))
// show only the currentStep
document.querySelector(`#step-${currentStep}`).style.display = 'block'
// hide or show the prevButton
if (currentStep === 1) {
prevButton.style.display = 'none'
} else {
prevButton.style.display = 'inline-block'
}
// hide or show nextButton & finish button
if (currentStep === totalSteps) {
nextButton.style.display = 'none'
finishButton.style.display = 'inline-block'
} else {
nextButton.style.display = 'inline-block'
finishButton.style.display = 'none'
}
}
function finish() {
console.log('you are finished')
}
<div class="step-container">
<div class="step" id="step-1">Hello</div>
<div class="step" id="step-2">Hi</div>
<div class="step" id="step-3">Salom</div>
<div class="step" id="step-4">Molas</div>
<button id="prevBtn" onclick="prevBtn()">back</button>
<button id="nextBtn" onclick="nextBtn()">next</button>
<button id="finishBtn" onclick="finish()">finish</button>
</div>
Something like this?
var activeButton = 0;
function next() {
document.getElementById(activeButton).classList.remove('active');
activeButton++;
document.getElementById(activeButton).classList.add('active');
}
function previous() {
document.getElementById(activeButton).classList.remove('active');
activeButton--;
document.getElementById(activeButton).classList.add('active');
}
.step {
display: none;
}
.active {
display: inline;
}
<button id="0" class="active step">First</button>
<button id="1" class="step">Second</button>
<button id="2" class="step">Third</button>
<button id="3" class="step">Fourth</button>
<button id="4" class="step">Fifth</button>
<button id="5" class="step">Sixth</button>
<button id="6" class="step">Seventh</button>
<hr>
<button id="next" onclick="next()">Next</button>
<button id="next" onclick="previous()">Previous</button>

What's a simple, non-jquery way to toggle between two divs using two buttons?

I'm looking for a simple, non-jquery method of toggling between two divs. Specifically, clicking button A will show div A content (and hide div B content), and clicking button B will show div B content (and hide div A content. I want div A content to appear by default when the page loads.
The code I have isn't hiding the appropriate divs from the onclick
I've looked around, but every solution seems overly complex or seems to involve jquery - which I would really prefer not to use, because I have to work with an old jquery library on a site where I shouldn't be updating that stuff.
<button class="button" onclick="content_A(); Hide_Content_B;">Content A</button>
<button class="button" onclick="content_B(); Hide_Content_A;">Content B</button>
<script>
function Content_A() {
var x = document.getElementById("A");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<script>
function Hide_Content_B() {
var x = document.getElementById("B");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
</script>
<script>
function Content_B() {
var x = document.getElementById("B");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<script>
function Hide_Content_A() {
var x = document.getElementById("A");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
</script>
<div id="A"> stuff</div>
<div id="B"> other stuff </div>
Create one function showContent that takes the id of the element you want
to toggle as parameter and just toggles a CSS class, i.e visible on the element with that id.
Use CSS classes to initially hide the "toggleable" elements. You can set the visible class directly on the element you want shown on page load.
Here's an example:
function showContent(id) {
document.getElementById(id).classList.toggle('visible')
}
/*
All elements with class "toggleable"
should be hidden.
*/
.toggleable {
display: none;
}
/*
All elements that have both
class "toggleable" and "visible"
should be visible.
*/
.toggleable.visible {
display: block;
}
<button onclick="showContent('a');" >Show Content A</button>
<button onclick="showContent('b');" >Show Content B</button>
<div class="toggleable visible" id="a">
Hello Content A!
</div>
<div class="toggleable" id="b">
Hello Content B!
</div>
About your code:
You have to call the function using parenthesis like Hide_Content_A() and Hide_Content_B(); which are misssing in onclick of the <button>
The functions Content_B and Content_B start with uppercase C.
The fix your own code, just run Hide_Content_B(); at the end to hide the second one.
Note that you can also use a single <script> block.
function Content_A() {
var x = document.getElementById("A");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function Hide_Content_B() {
var x = document.getElementById("B");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
function Content_B() {
var x = document.getElementById("B");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function Hide_Content_A() {
var x = document.getElementById("A");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
Hide_Content_B();
<button class="button" onclick="Content_A(); Hide_Content_B();">Content
A
</button>
<button class="button" onclick="Content_B(); Hide_Content_A();">Content
B
</button>
<div id="A"> stuff</div>
<div id="B"> other stuff</div>
If you dont want to use jQuery, you should consider not using javascript at all.
You can do the same with pure css. Also the styling of button tags some times brakes in other devices, so I suggest to use tag or just a span
Here is a pure CSS solution:
input {
display:none;
}
input[name="toggle"] + .toggleContent{
max-height: 0;
overflow: hidden;
transition: max-height .4s;
}
input[name="toggle"]:checked + .toggleContent{
max-height: 100px;
}
<label for="A">A Button</label>
<input type="radio" name="toggle" value="1" id="A" checked="checked">
<div class="toggleContent">This is content for A</div>
<label for="B">B Button</label>
<input type="radio" name="toggle" value="2" id="B">
<div class="toggleContent">This is content for B</div>
Here's a simple solution that requires jQuery 1.7 or above, since you mentioned that you're working with an old jQuery library!
$(document).on('click', '.map-point-sm', function() {
var show = $(this).data('show');
$(show).removeClass("hide").siblings().addClass("hide");
});
.hide {
display: none;
}
.map-container {
text-align: center;
}
button{
width: 5%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div class="map-container">
<div class="inner-basic division-map div-toggle" data-target=".division-details" id="divisiondetail">
<button class="map-point-sm" data-show=".a">
<div class="content">
<div class="centered-y">
<p>A</p>
</div>
</div>
</button>
<button class="map-point-sm" data-show=".b">
<div class="content">
<div class="centered-y">
<p>B</p>
</div>
</div>
</button>
</div>
</div>
<div class="map-container">
<div class="inner-basic division-details">
<div class="initialmsg">
<p>A Content here</p>
</div>
<div class="a hide">
<p>A Content here</p>
</div>
<div class="b hide">
<p>B Content here</p>
</div>
</div>
</div>
There are some great answers here, but I think I'll probably go with The fourth bird's because it's the simplest. Thanks everybody!
If you are interested in a non-JS solution, you can use sibling input elements to perform a button toggle effect. Simply match the for attributes with the id attributes.
form {
display: flex;
flex-wrap: wrap;
}
input {
display: none;
}
input:checked + label {
background-color: #eee;
}
label {
cursor: pointer;
padding: 12px;
display: inline-block;
}
.container {
display: none;
background-color: #eee;
order: 1;
padding: 12px;
width: 100%;
}
input:checked + label + .container {
display: block;
}
<form>
<input id="a" type="radio" name="container" checked="checked">
<label for="a">button a</label>
<div class="container">content a</div>
<input id="b" type="radio" name="container">
<label for="b">button b</label>
<div class="container">content b</div>
</form>

TOGGLE 2 DIVS with a Button (Using Javascript, HTML and CSS)

Basically I have 2 divs both with different contents inside and I'd like to toggle between them with a button.
I have here my 2 divs with class "step1Content" and "step2Content" respectively.
<div class = 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>
I gave step1Content the style display: block.
.step1Content { display: block; }
I gave step2Content the style display: none.
.step2Content { display: none; }
I have a button that would toggle between these 2 to show or hide.
<button onclick = 'step2()'>2. Taskeros and Prices</button>
And my javascript function:
function step2(){
document.getElementByClassName('step1Content').style.display = 'none';
document.getElementByClassName('step2Content').style.display = 'block';
}
You'd think the results would be a okay right? Nope, when I click the button it does literally nothing. I have no idea why, any help with this?
Keep in mind that
getElementsByClassName
will return a collection of all elements in the document with the specified class name, as a NodeList object.
You can either use getElementById or querySelector
Here's a working solution. Hope it helps!
function step2(){
if(document.querySelector('.step1Content').style.display === "none"){
document.querySelector('.step2Content').style.display = 'none';
document.querySelector('.step1Content').style.display = 'block';
}else{
document.querySelector('.step1Content').style.display = 'none';
document.querySelector('.step2Content').style.display = 'block';
}
}
.step1Content { display: block; }
.step2Content { display: none; }
<button onclick = 'step2()'>2. Taskeros and Prices</button>
<div class= 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>
The function is getElementsByClassName not getElementByClassName and it returns array-like collection of elements. so you need to use index 0 here for the first element.
function step2(){
var element=document.getElementsByClassName('step1Content');
element[0].style.display = (element[0].style.display ==='none') ? 'block' : 'none';
var element1= document.getElementsByClassName('step2Content');
element1[0].style.display = (element1[0].style.display ==='block') ? 'none' : 'block';
}
.step1Content { display: block; }
.step2Content { display: none; }
<div class = 'step1Content'> Content1 </div>
<div class = 'step2Content'> AnotherContent </div>
<button onclick = 'step2()'>2. Taskeros and Prices</button>
If you want to toggle visibility of div then you can use j-query toggle function.
Please read http://api.jquery.com/toggle/
$("button").click(function(){
$("#shay").toggle();
});
For Toggling two div -
CSS - .show { display: block; } .hide { display: none; }
$("button").click(function(){
$('#div1').toggle();
$('#div2').toggle();
});
</script>
<body>
<div class="hide" id="div1">Hi Div1</div>
<div class="show" id="div2">Hi Div2</div>
<button>Click me</button>
You can use Array.prototype.reverse() to toggle display of div elements
.step1Content {
display: block;
}
.step2Content {
display: none;
}
<button onclick='step2()'>2. Taskeros and Prices</button>
<div class='step1Content'>Content1</div>
<div class='step2Content'>AnotherContent</div>
<script>
var divs = Array.from(document.querySelectorAll("div[class^=step]"));
function step2() {
divs[0].style.display = "none";
divs[1].style.display = "block";
divs.reverse();
}
</script>

Categories