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

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>

Related

JavaScript Function

Hello everybody I have this code that I have made alone.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
function myFunction() {
var itm = document.getElementById("myList2").lastChild;
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
width: 300px;
height: 300px;
background-color: red;
}
<!DOCTYPE html>
<html>
<body>
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="">DELETE</button>
<div id="myList2">
<div id="test">
</div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>
</body>
</html>
What I want to make is that the red square whenever you are clicking on the ADD button it will be a clone and when you click on the DELETED button that the clone is deleted. Can somebody help me, please?
In addition to missing } as was mentioned in the comments, there was a not-so-obvious problem with finding the <div> to clone. The lastChild was actually a text node containing the \n (newline), after the <div>. It's better to search for <div> by tag:
var itm = document
.getElementById('myList2')
.getElementsByTagName('div')[0];
Since there's only one <div> we can use the zero index to find this first and only one.
And for delete function you can use a similar approach and get the last <div> and remove it.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
}
function myFunction() {
var itm = document.getElementById("myList2").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function deleteFunction() {
var list1 = document.getElementById("myList1");
var divs = Array.from(list1.getElementsByTagName("div"));
// If the number of divs is 3, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 3) {
document.getElementById("button").style.display = "none";
}
var lastDivToDelete = divs[divs.length - 1];
list1.removeChild(lastDivToDelete);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
/* make it smaller so it's easier to show in a snippet */
width: 30px;
height: 30px;
background-color: red;
}
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="deleteFunction()">DELETE</button>
<div id="myList2">
<div id="test"></div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>

button toggle display show hide

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>

How to control execution order when two events are triggered at the same time

This is a simple drop-down menu with input in HTML and pure javascript (no JQuery). I don't want to use the pre-defined HTML list with option tags because i need scroll bars, styling etc.
I hide the list onblur but this event gets triggered before the click on the items list. So the result is that I cant click on the items of the drop-down menu because the list gets hidden before hand.
This is the code:
function showList(){
elem = document.getElementById("list");
elem.className = "unhidden";
}
function hideList(){
elem = document.getElementById("list");
elem.className = "hidden";
}
function showSuccess(){
elem = document.getElementById("successDiv");
elem.innerHTML = "code successful!";
}
.hidden { display: none; }
.unhidden { display: block; }
<html>
<head>
</head>
<body>
<input onfocus="showList();" onblur="hideList();"/>
<div id="list" class="hidden">
click for success
</div>
<div id="successDiv">
</div>
</body>
</html>
The easiest solution is to add a small delay with setTimeout before hiding the element. In the example below i wait a 250 milliseconds before removing the class.
function showList(){
elem = document.getElementById("list");
elem.className = "unhidden";
}
function hideList(){
setTimeout(function() {
elem = document.getElementById("list");
elem.className = "hidden";
}, 250); // Wait 250 milliseconds
}
function showSuccess(){
elem = document.getElementById("successDiv");
elem.innerHTML = "code successful!";
}
.hidden { display: none; }
.unhidden { display: block; }
<html>
<head>
</head>
<body>
<input onfocus="showList();" onblur="hideList();"/>
<div id="list" class="hidden">
click for success
</div>
<div id="successDiv">
</div>
</body>
</html>
EDIT: More robust solution
You can look at the events relatedTarget and if it is inside the list dont close it before clicking on it.
const input = document.querySelector("#input");
const list = document.querySelector("#list");
const listItems = document.querySelectorAll("#list a");
const success = document.querySelector("#successDiv");
input.addEventListener("focus", showList);
input.addEventListener("blur", hideList);
for(const listItem of listItems) {
listItem.addEventListener("click", showSuccess);
}
function showList() {
list.classList.remove("hidden");
}
function hideList(event) {
if(event.relatedTarget?.parentNode !== list) {
list.classList.add("hidden");
}
}
function showSuccess(event) {
success.innerHTML = "code successful!";
// Remove line to keep list open
hideList(event);
}
#list {
display: flex;
flex-direction: column;
}
#list.hidden { display: none; }
<input id="input" />
<div id="list" class="hidden">
click for success
click for more success
click for even more success
</div>
<div id="successDiv">
</div>

How to hide all divs of same class using onclick? [duplicate]

This question already has answers here:
Equivalent of getElementById for Classes in Javascript
(6 answers)
Closed 2 years ago.
As you can see by running the snippet 1 div isn't hiding , I'm a newbie so I don't know what to do? Can someone explain what's wrong? I can't figure it out.
var x = document.getElementById("jobs");
function openandcloseavjobs() {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#jobs{
height: 100px;
width:100px;
background-color:orange;
margin: 20px;
}
<button onclick="openandcloseavjobs()">Average Pay</button>
<div id="jobs">
<h3>job 1</h3>
</div>
<div id="jobs">
<h3>job 2</h3>
</div>
You need to use a class and use querySelectorAll method to get all element with same class name .jobs using forEach function to loop through all the elements and then use display none or block on all found element with that class name.
Also, where possible do not use inline events like onClick etc use addEventListener with a click instead.
Live Demo:
var getEl = document.querySelectorAll(".jobs"); //get all element .jobs
var btn = document.querySelector("#getAvg"); //get the btn
//Button click function
btn.addEventListener('click', function() {
getEl.forEach(function(item) { //forEach elements
if (item.style.display === "none") {
item.style.display = "block";
} else {
item.style.display = "none";
}
})
}, false);
.jobs {
height: 100px;
width: 100px;
background-color: orange;
margin: 20px;
}
<button id="getAvg">Average Pay</button>
<div class="jobs">
<h3>job 1</h3>
</div>
<div class="jobs">
<h3>job 2</h3>
</div>
The problem is that the function getElementById only finds 1 element as the name suggests.
You should try with class names so change the to and use the function getElementsByClassName("example").
You are using id (identifier, which, by definition should be unique) to select multiple elements. To achieve what you want, use a class
var X = document.getElementsByClassName("jobs");
function openandcloseavjobs() {
for (let x of X) {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
.jobs{
height: 100px;
width:100px;
background-color:orange;
margin: 20px;
}
<button onclick="openandcloseavjobs()">Average Pay</button>
<div class="jobs">
<h3>job 1</h3>
</div>
<div class="jobs">
<h3>job 2</h3>
</div>

toggle hidden : unhidden not working with JS in HTML/CSS?

http://jsfiddle.net/bDQt7/1/
Toggle hidden : unhidden doesn't work, and I can't figure out why?
html
Toggle
<div id="top">
<div id="menu" class="hidden">
hello
</div>
</div>
css
.hidden {
display: none;
}
.unhidden {
display: block;
}
JS
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className = (item.className == 'hidden') ? 'unhidden' : 'hidden';
}
}
Try
Wrap code in body or head below your html.
Working fidde

Categories