js toggle for multiple divs - javascript

I have 3 div which are hidden by default. I want to create a toggle for these 3 but I don't want to create onclick for each div and add this to the js file:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
I tried creating this scenario with clicked_id but it failed. When I click on the third div, the second one views aswell.
var projectEen = document.getElementById("projectInhoud");
projectEen.style.display = "none";
var projectTwee = document.getElementById("projectInhoudTwee");
projectTwee.style.display = "none";
var projectDrie = document.getElementById("projectInhoudDrie");
projectDrie.style.display = "none";
function displayFunction(clicked_id) {
if (clicked_id == 1) {
projectEen.style.display = "block";
} else {
projectTwee.style.display = "block";
} if(clicked_id == 3) {
projectDrie.style.display = "block";
} else {
projectTwee.style.display = "none";
}
}
How can I use the first code but to display all 3 div without creating the function 3 times?
EDIT:
My html
<div id="1" onclick="displayFunction(this.id)" class="projectTitel">
<h1>Project: a</h1>
</div>
<div id="projectInhoudEen" class="projectInhoud"> content </div>
<div id="2" onclick="displayFunction(this.id)" class="projectTitel">
<h1>Project: b</h1>
</div>
<div id="projectInhoudTwee" class="projectInhoud"> content </div>
<div id="3" onclick="displayFunction(this.id)" class="projectTitel">
<h1>Project: c</h1>
</div>
<div id="projectInhoudDrie" class="projectInhoud"> content </div>

By combining document.getElementsByClassName and EventTarget.addEventListener, you can attach the same event handler to your divs. Inside this handler, you can retrieve the element you clicked on with the event object, provided by the event listener.
EDIT : The HTML you provided makes things a little more complicated because the projectTitel and projectInhoud divs aren't related to each other, except by position.
So, in order to display the right projectInhoud div, we need to find the next projectInhoud after the projectTitel that was clicked on.
To make things better, I would suggest editing the HTML to make projectTitel and projectInhoud divs children of a same parent div.
Meanwhile, I added a getClickedProjectIndex function returns the index of the clicked projectTitel div. And the click event uses this index to show the right projectInhoud.
Then, you can use a simple toggle function that displays the div if it's not visible or hide it if it's visible.
var divs = document.getElementsByClassName("projectTitel");
[...divs].forEach(someDiv => someDiv.addEventListener("click", handler));
// by default, all projectInHound are hidden
hideElements("projectInhoud");
function handler(event) {
// get the clicked project's index :
var projectIndex = getClickedProjectIndex(event);
// toggle the right projectInhoud div :
toggleDiv(document.getElementsByClassName("projectInhoud")[projectIndex]);
}
// hide all elements that have the provided class name
function hideElements(className) {
var elements = document.getElementsByClassName(className);
[...elements].forEach(element => element.style.display = "none");
}
function getClickedProjectIndex(event) {
var elements = document.getElementsByClassName("projectTitel");
var projectIndex = 0;
[...elements].forEach((element, index) => {
if (element.id == event.currentTarget.id) {
projectIndex = index;
}
});
return projectIndex;
}
function toggleDiv(element) {
if (element.style.display === 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
<div id="1" class="projectTitel">
<h1>Project: a</h1>
</div>
<div id="projectInhoudEen" class="projectInhoud" > content a</div>
<div id="2" class="projectTitel">
<h1>Project: b</h1>
</div>
<div id="projectInhoudTwee" class="projectInhoud"> content b</div>
<div id="3" class="projectTitel">
<h1>Project: c</h1>
</div>
<div id="projectInhoudDrie" class="projectInhoud"> content c</div>

I would try something like this in the HTML:
<div class=myDiv onclick=myFunction(this)></div>
<div class=myDiv onclick=myFunction(this)></div>
<div class=myDiv onclick=myFunction(this)></div>
And for your JavaScript:
function myFunction(element){
if(element.style.display = "none"){
element.style.display = "block";
else{
element.style.display = "none";
}
}

Related

I want to hide a div using javascript

I created a div contaning a form and a button. I want to hide the entire div when the button is clicked.
function myFunction() {
let x = document.querySelector("div");
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<div onmouseover="firstPageDisplay();" id="firstPage">
<div><img id="imgs"></div>
<div class="center">
<form class="center">Authentification<br>
<p>Login</p> <input id="login" type="text"><br>
<p>Password</p> <input id="password" type="password"><br><br>
<button onclick="myFunction();" id="btnA">Se connecter</button>
</form>
</div>
</div>
This is what I tried to do, however when I click the button, the div disappears for a split second then reappears again. When I removed the button from the div it worked just fine. How can I make it disappear for good?
you have document.querySelecor('div') which is selecting the first <div> in the whole document, probably not what you want.
the error is here
function myFunction() {
let x = document.querySelector("div");
if (x.style.display == "none") { // error
x.style.display = "block";
} else {
x.style.display = "none";
}
}
you can only set a style, not get a style. Why? Because reasons nobody with common sense will understand. so instead you have to use getComputedStyle(element).styleName
function myFunction() {
let x = document.querySelector("div"); // if this is div you want
if (getComputedStyle(x).display == "none") { // 👍👍👍
x.style.display = "block";
} else {
x.style.display = "none";
}
}
but as mentioned in a comment above, toggling a class and using event listeners are much better practice

Simple hide/show div+js : how to start hidden?

I have a Hide/show div with a button and javascript code. I want to start it hidden (and not show).
can you help me ?
HTML
Click Me
<div id="myDIV">
This is my DIV element.
</div>
JAVASCRIPT
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
this is were i have found the code : hide/show
put onload in body
<body onload="myFunction()">

3 Buttons show/hide 3 div's in javascript

I used one of the codes I found in this website for creating 3 buttons which hided and showed 3 different div's. Code I found was created for 2 div's, so I've tried to edit it to support 3 div's. At first, it looked like it works, but then I noticed one problem: when you click on button which shows first or second div, everything in that div is clickable and when you click on something inside div, it open third div for no reason, how to fix that? Text inside div should not be clickable. Here's link for example of that problem:
http://www.llbm.lt/etnografiniai_regionai/mazoji_lietuva.html
Here's code:
<div class="trys-mygtukai">
<a "href="#" onclick="return showHide();"><img SRC="/etnografiniai_regionai/img/informacija_button.png"</a>
<a "href="#" onclick="return showHide1();"><img SRC="/etnografiniai_regionai/img/architektura_button.png"</a>
<a "href="#" onclick="return showHide2();"><img SRC="/etnografiniai_regionai/img/kita_button.png"</a>
</div>
<div id="pirmas" style="display:none;"></div>
<div id="antras" style="display:none;"></div>
<div id="trecias" style="display:none;"></div>
<script type="text/javascript" language="javascript">
function showHide() {
var ele = document.getElementById("pirmas");
var ele1 = document.getElementById("antras");
var ele2 = document.getElementById("trecias");
ele1.style.display = "none";
ele2.style.display = "none";
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
function showHide1() {
var ele = document.getElementById("pirmas");
var ele1 = document.getElementById("antras");
var ele2 = document.getElementById("trecias");
ele.style.display = "none";
ele2.style.display = "none";
if(ele1.style.display == "block") {
ele1.style.display = "none";
}
else {
ele1.style.display = "block";
}
}
function showHide2() {
var ele = document.getElementById("pirmas");
var ele1 = document.getElementById("antras");
var ele2 = document.getElementById("trecias");
ele.style.display = "none";
ele1.style.display = "none";
if(ele2.style.display == "block") {
ele2.style.display = "none";
}
else {
ele2.style.display = "block";
}
}
You aren't closing the image tags properly
<a "href="#" onclick="return showHide2();"><img SRC="/etnografiniai_regionai/img/kita_button.png"</a>
This should be:
<img SRC="/etnografiniai_regionai/img/kita_button.png">
You made the same mistake with the other 2 images as well, after closing them this behaviour should disappear.
As said before: youre not closing the img tag properly, also this might bug your code:
"href="#" should be href="#"

Change style.display on multiple objects through one button JAVASCRIPT

im trying to change the display attribute of multiple objects through one button, using event listener. It works fine if I just want to change the display on one object at a time but not all three..
any ideas?
http://jsfiddle.net/rn9vrwyg/
var ruta1 = document.getElementById('ruta1')
var ruta2 = document.getElementById('ruta2')
var ruta3 = document.getElementById('ruta3')
document.getElementById('knapp1').addEventListener("click", function(){
ruta1.style.display = "block";
ruta2.style.display = "none";
ruta3.style.display = "none";
});
document.getElementById('knapp2').addEventListener("click", function(){
ruta2.style.display = "block";
ruta1.style.display = "none";
ruta3.style.display = "none";
});
document.getElementById('knapp3').addEventListener("click", function(){
ruta3.style.display = "block";
ruta1.style.display = "none";
ruta2.style.display = "none";
});
<div id="ruta1">
<p>Informationbox #1</p>
</div>
<div id="ruta2">
<p>Informationbox #2</p>
</div>
<div id="ruta3">
<p>Informationbox #3</p>
</div>
These div's and p tags are not closed properly. Close those tags then its working as expected.

Don't show more than one div at a time Javascript

I currently have four divs, which are each linked to a hidden div:
div1 - div1hidden
div2 - div2hidden
div3 - div3hidden
div4 - div4hidden
When a user clicks on one of the divs the hidden div appears. When clicked on again the div disappears.
The problem I have is if all four divs are clicked on all four hidden will appear. What I would like to do is only show one at a time.
For Example if 'div1hidden' is showing and the user clicks on div2 before hiding div1hidden, div1hidden will hide and div2hidden will appear.
This is the code I have so far:
function hide_menu(id){document.getElementById(id).style.display = "none";}
function show_menu(id){document.getElementById(id).style.display = "block";}
<div class="div1" onclick="if (document.getElementById('div1hidden').style.display=='none') show_menu('div1hidden'); else hide_menu('div1hidden');"></div>
<div class="div2" onclick="if (document.getElementById('div2hidden').style.display=='none') show_menu('div2hidden'); else hide_menu('div2hidden');"></div>
<div class="div3" onclick="if (document.getElementById('div3hidden').style.display=='none') show_menu('div3hidden'); else hide_menu('div3hidden');"></div>
<div class="div4" onclick="if (document.getElementById('div4hidden').style.display=='none') show_menu('div4hidden'); else hide_menu('div4hidden');"></div>
Thanks in advance
Rick
Try something like this:
Add a function:
function hide_all() {
hide_menu('div1hidden');
hide_menu('div2hidden');
hide_menu('div3hidden');
hide_menu('div4hidden');
}
Now call that function before you show any hidden div:
<div class="div1" onclick="if (document.getElementById('div1hidden').style.display=='none') {hide_all(); show_menu('div1hidden'); } else { hide_menu('div1hidden'); }"></div>
I'm not sure what's wrong with just hiding all other divs before opening the one your need:
<div class="div1" onclick="if (document.getElementById('div1hidden').style.display=='none') { hide_menu('div2hidden'); hide_menu('div3hidden'); hide_menu('div4hidden'); show_menu('div1hidden');} else hide_menu('div1hidden');"></div>
<!-- and so on -->
I must say that this isn't exactly the best approach to do the comparison in the onclick - instead I suggest putting it inside the function, something like this:
<script type="text/javascript">
function flipDiv(id)
{
var vis = document.getElementById('div' + id + 'hidden').style.display;
if(vis == 'none')
{
document.getElementById('div1hidden').style.display = 'none';
document.getElementById('div2hidden').style.display = 'none';
document.getElementById('div3hidden').style.display = 'none';
document.getElementById('div4hidden').style.display = 'none';
document.getElementById('div' + id + 'hidden').style.display = 'block';
}
else
{
document.getElementById('div' + id + 'hidden').style.display = 'block';
}
}
</script>
...
<div class="div1" onclick="flipDiv(1)">...</div>
...
The easiest way will be to cache the current open menu.
<head>
<script type="text/javascript">
var current = null; //current is stored here
function hide_current(){
if(current !=null){
document.getElementById(current).style.display = "none";
}
}
function show_menu(id){
if(current == id){
hide_current(); //current is already open, close it
current = null; //reset current
} else {
document.getElementById(id).style.display = "block";
current = id;
}
}
</script>
</head>
<body>
<div class="div1" onclick="hide_current();show_menu('div1hidden');"></div>
<div class="div2" onclick="hide_current();show_menu('div2hidden');"></div>
<div class="div3" onclick="hide_current();show_menu('div3hidden');"></div>
<div class="div4" onclick="hide_current();show_menu('div4hidden');"></div>
</body>
Although the other suggested answers will accomplish what you want, none of them are very robust. This is based on the fact that your sample code is not very robust. It relies on inline javascript calls and hard coding to your elements.
Something like this will be easily extendable and less prone to breakage. Please note that some modifications will be necessary to accommodate old versions of IE (attachEvent support and getElementsByClassName support). But the concepts are the important thing.
Basically we get all the parent divs. Attach an event to their click. When they are clicked we hide all the divs that are supposed to be hidden and show the one we want.
http://jsfiddle.net/mrtsherman/8sgC2/2/
var divs = document.getElementsByClassName('menu');
for (var index = 0; index < divs.length; index++) {
divs[index].addEventListener('click', function() {
var contentDiv = null;
//hide all other divs
for (var i = 0; i < divs.length; i++) {
contentDiv = document.getElementById(divs[i].id + 'content');
contentDiv.style.display = 'none';
}
//show current item
contentDiv = document.getElementById(this.id + 'content');
contentDiv.style.display = 'block';
}, false)
}
<div class="menu" id="div1">one</div>
<div class="menu" id="div2">two</div>
<div class="menu" id="div3">three</div>
<div class="menu" id="div4">four</div>
<div class="content" id="div1content">one content</div>
<div class="content" id="div2content">two content</div>
<div class="content" id="div3content">three content</div>
<div class="content" id="div4content">four content</div>
Note that libaries like jQuery can do this in far less code, without having to account for browser differences and with cool effects like sliding or fading in.
http://jsfiddle.net/mrtsherman/8sgC2/3/
//bind to click event on the div
$('.menu').click( function() {
//get content div associated with the clicked div
var contentDiv = $(this).attr('id') + 'content';
//if no items are visible yet then show current
if ($('.content').filter(':visible').length == 0) {
$('#' + contentDiv).slideDown();
return;
}
//hide visible divs and show new div
$('.content').filter(':visible').slideUp('fast', function() {
$('#' + contentDiv).slideDown();
});
});
You can create the Display Div & Hidden div
at the same time and creating the click event in loop
This is source code which you can use to apply for unlimited divs
var n = 10;
var did = 'divDisplay';
var hid = 'divHidden';
function divDisplayOnclick()
{
for(var i=0; i<n; i++)
{
document.getElementById(did+i+hid).style.display = 'none';
}
document.getElementById(this.id+hid).style.display = 'block';
}
function createDivDisplay()
{
for(var i=0; i<n;i++)
{
var divDisplay = document.createElement('div');
divDisplay.id = did+i;
divDisplay.innerHTML = 'Click to display hidden div '+i;
divDisplay.className = did;
divDisplay.onclick = divDisplayOnclick;
document.body.appendChild(divDisplay);
var divHidden = document.createElement('div');
divHidden.id = did+i+hid;
divHidden.innerHTML = 'This is hidden div '+i;
divHidden.className = hid;
document.body.appendChild(divHidden);
}
}
createDivDisplay();
.divDisplay
{
border: 1px solid powderblue;
margin-bottom: 5px;
cursor: pointer;
}
.divHidden
{
border: 1px solid red;
margin-left: 20px;
margin-bottom: 10px;
display: none;
}

Categories