How to toggle close all divs when another div is opened - javascript

I have a long streak of divs with the following structure:
<div id="income">
<h5 onclick="toggle_visibility('incometoggle');">INCOME</h5>
<div id="incometoggle">
<h6>Income Total</h6>
</div>
</div>
<div id="income2">
<h5 onclick="toggle_visibility('incometoggle2');">INCOME2</h5>
<div id="incometoggle2" style="display:none;">
<h6>Income Total2</h6>
</div>
</div>
<div id="income3">
<h5 onclick="toggle_visibility('incometoggle3');">INCOME3</h5>
<div id="incometoggle3" style="display:none;">
<h6>Income Total3</h6>
</div>
</div>
I have this code to make them open and close:
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
}
At site load, the first div is opened, the rest is closed.
http://jsfiddle.net/txa2x9qq/3/
How can I make the first div close when the second one is opened, and so on - to have only one opened at a time?
Thank you

This way you just open the next on the close of the previus
function toggle_visibility(id,next) {
var e = document.getElementById(id);
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
if (next != undefined)
{
toggle_visibility(next);
}
}
call it like:
<h5 onclick="toggle_visibility('incometoggle','incometoggle2');">INCOME</h5>
http://jsfiddle.net/txa2x9qq/3/

You can use jQuery Start with Selector to hide all div starting with incometoggle and use not() to exclude the current div
See below function
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'none') e.style.display = 'block';
else e.style.display = 'none';
// hide all div except current
$('div[id^=incometoggle]').not('#'+id).hide();
}
DEMO
EDIT - you can write whole logic in jQuery only, just bind click event to h5 elements and show / hide div next to it using toggle. And hide all div except current using jQuery Start with Selector
$(function() {
$('h5').click(function(){
var incomeDiv = $(this).next('div');
$(incomeDiv).toggle();
$('div[id^=incometoggle]').not(incomeDiv).hide();
});
});
DEMO Using JQuery

You can use jQuery more easily:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function toggle_visibility(id) {
$("div[id^='incometoggle']").hide();
$('#'+id).show();
}
</script>

I would approach it slightly differently and use a class along with a jquery selector -
<div id="income">
<h5 onclick="toggle_visibility('incometoggle');">INCOME</h5>
<div id="incometoggle" class="income-total">
<h6>Income Total</h6>
</div>
</div>
...
function toggle_visibility(id) {
// hide all divs with class income-total
$('.income-total').hide();
// show the desired div
$('#' + id).show();
}

Using just Vanilla Javascript, like you're actually doing at the moment:
function toggle_visibility(id) {
// Your clicked element
var e = document.getElementById(id);
// List containing all the divs which id starts with incometoggle.
var allDivs = document.querySelectorAll('div[id^=incometoggle]');
// Loop through the list and hide the divs, except the clicked one.
[].forEach.call(allDivs, function(div) {
if (div != e) {
div.style.display = 'none';
}
else {
e.style.display = e.style.display == 'none' ? 'block' : 'none';
}
});
}
Demo

If you want to do in pure java script then this solution will work for you.
<div id="income">
<h5 onclick="toggle_visibility('incometoggle');">INCOME</h5>
<div id="incometoggle" class="income">
<h6>Income Total</h6>
</div>
</div>
<div id="income2">
<h5 onclick="toggle_visibility('incometoggle2');">INCOME2</h5>
<div id="incometoggle2" style="display:none;" class="income">
<h6>Income Total2</h6>
</div>
</div>
<div id="income3">
<h5 onclick="toggle_visibility('incometoggle3');">INCOME3</h5>
<div id="incometoggle3" style="display:none;" class="income">
<h6>Income Total3</h6>
</div>
</div>
function toggle_visibility(id) {
var e = document.getElementById(id);
var myClasses = document.querySelectorAll('.income'),
i = 0,
l = myClasses.length;
for (i; i < l; i++) {
myClasses[i].style.display = 'none';
}
if (e.style.display == 'none') e.style.display = 'block';
}
DEMO

Related

My sidenav color isn't changing with the button (onclick)

I created a JS Script that change the background of my side menu by clicking a button but it doesn't change anything
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function toggle_visibility() {
var e = document.getElementById('on');
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
var f = document.getElementById('off');
if(f.style.display =='block')
f.style.display = 'none';
else
f.style.display = 'block';
var g = document.getElementById('sidenav');
if(g.style.background == '#F5F5F5') {
g.style.background = '#252525';
}
if(g.style.background == '#252525') {
g.style.background = '#F5F5F5';
}
}
</script>
</head>
<body id='body'>
<div id="sidenav" style="background: #F5F5F5">
<div class="btn-area" onclick="toggleNav()">&#9776</div>
<ul>
<div class="button">
<button onclick="changeColor(); backgroundHiding(); toggle_visibility();" class="lightbutton">
<span id="on">Turn Off the lights</span>
<span id="off" style="display: none">Turn On the lights</span>
</button>
</div>
</ul>
</div>
</body>
</html>
I expected it to change my background to the id='sidenav' but it didn't change anything...
I would appreciate if someone helps me
uwu
So you can accomplish this by a little modification to your styles and the JS. Just use g.classList.toggle('lights-on'). Creating classes is better than inline styles as well. Make sure you give the sidenav the starting class of lights-on.
Here is the complete code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function toggle_visibility() {
var e = document.getElementById('on');
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
var f = document.getElementById('off');
if(f.style.display =='block')
f.style.display = 'none';
else
f.style.display = 'block';
var g = document.getElementById('sidenav');
g.classList.toggle('lights-off'); //<--- here is the toggle instead of your ifs
}
</script>
</head>
<body id='body'>
<div id="sidenav" class="lights-on"> <!-- make sure you add this class -->
<div class="btn-area" onclick="toggleNav()">&#9776</div>
<ul>
<div class="button">
<button onclick="changeColor(); backgroundHiding(); toggle_visibility();" class="lightbutton">
<span id="on">Turn Off the lights</span>
<span id="off" style="display: none">Turn On the lights</span>
</button>
</div>
</ul>
</div>
</body>
</html>
and your stylesheet should be something like this:
.lights-on {
background-color: #f5f5f5;
}
.lights-off {
background-color: #252525;
}
as a side note I would suggest using consistent naming for your methods so toggle_visibility() should be toggleVisibility().
The problem is this if-statement inside the toggle_visibility function
if(g.style.background == '#F5F5F5')
.background doesn't refer to the color only. It can hold up to eight individual properties.
For example if you log this
console.log(g.style.background);
you will see the following string
rgb(245, 245, 245) none repeat scroll 0% 0%
in the console.
That means the comparison if(g.style.background == '#F5F5F5') won't ever be true.
Furthermore as you can see from the above it returns a rgb value instead of a hex number so you need to convert the color to hex first.
There's a handy library which does the job w3color
Here's the complete example:
function toggle_visibility() {
var e = document.getElementById('on');
if (e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
var f = document.getElementById('off');
if (f.style.display == 'block')
f.style.display = 'none';
else
f.style.display = 'block';
var g = document.getElementById('sidenav');
if (w3color(g.style.backgroundColor).toHexString().toUpperCase() == '#F5F5F5') {
g.style.backgroundColor = '#252525';
} else
if (w3color(g.style.backgroundColor).toHexString().toUpperCase() == '#252525') {
g.style.backgroundColor = '#F5F5F5';
}
}
<script src="https://www.w3schools.com/lib/w3color.js"></script>
<div id="sidenav" style="background-color: #F5F5F5">
<div class="btn-area" onclick="toggleNav()">&#9776</div>
<ul>
<div class="button">
<button onclick="; toggle_visibility();" class="lightbutton">
<span id="on">Turn Off the lights</span>
<span id="off" style="display: none">Turn On the lights</span>
</button>
</div>
</ul>
</div>
use console.log(g.style.background) and you will see that g.style.background returns an rgb value not an HEX value like you expect.
So your code fails here:
var g = document.getElementById('sidenav');
if(g.style.background == '#F5F5F5') {
g.style.background = '#252525';
}
if(g.style.background == '#252525') {
g.style.background = '#F5F5F5';
}

Show/Hide Javascript one at a time

This is probably very simple but I'm at a loss.
I have two anchors that toggle the display of their own div containers. Right now, you can have both div containers showing by clicking each button once. I would like only one div showing at a time.
So if you select button 1 to show div 1, then you select button 2, it will show div 2 but also hide div 1.
Here is my code:
<script type="text/javascript" language="JavaScript">
function ReverseDisplay(d)
{
if(document.getElementById(d).style.display == "none")
{ document.getElementById(d).style.display = "block"; }
else
{ document.getElementById(d).style.display = "none"; }
}
</script>
<a id="menus" href="javascript:ReverseDisplay('menuList')">Button 1</a>
<a id="reso" href="javascript:ReverseDisplay('resoList')">Button 2</a>
<p>Some content</p>
<div id="menuList" style="display:none;">Some content</div>
<div id="resoList" style="display:none;">Some content</div>
Give div's common class
<div id="menuList" class="content" style="display:none;">Some content 1</div>
<div id="resoList" class="content" style="display:none;">Some content 2</div>
And then hide all before showing specific:
function ReverseDisplay(d) {
[].slice.call(document.querySelectorAll('.content')).forEach(function(el) {
el.style.display = 'none';
});
var element = document.getElementById(d);
element.style.display = element.style.display == "none" ? "block" : "none";
}
Check the demo below.
function ReverseDisplay(d) {
[].slice.call(document.querySelectorAll('.content')).forEach(function(el) {
el.style.display = 'none';
});
var element = document.getElementById(d);
element.style.display = element.style.display == "none" ? "block" : "none";
}
.content {
padding: 10px;
background: #EEE;
}
<a id="menus" href="javascript:ReverseDisplay('menuList')">Button 1</a>
<a id="reso" href="javascript:ReverseDisplay('resoList')">Button 2</a>
<p>Some content</p>
<div id="menuList" class="content" style="display:none;">Some content 1</div>
<div id="resoList" class="content" style="display:none;">Some content 2</div>
A bit more digging and I found a solution:
<script type="text/javascript" language="JavaScript">
(function() {
var opened_element = null;
window.ReverseDisplay = function(d) {
var e = document.getElementById(d);
if (opened_element && opened_element !== e) {
opened_element.style.display = 'none';
}
if(e.style.display == 'block') {
e.style.display = 'none';
}
else {
e.style.display = 'block';
}
opened_element = e;
};
}());</script>
You could
function ReverseDisplay(d) {
var el = document.getElementById(d),
els = document.getElementsByClassName('list'),
c;
for (var i = 0; i < els.length; i++) {
c = els[i];
if (el == c) {
if (el.style.display == "block") {
el.style.display = "none";
} else {
el.style.display = "block";
}
} else {
c.style.display = "none";
}
}
}
.list {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="menus" href="javascript:ReverseDisplay('menuList')">Button 1</a>
<a id="reso" href="javascript:ReverseDisplay('resoList')">Button 2</a>
<p>Some content</p>
<div id="menuList" class="list">Some content 1</div>
<div id="resoList" class="list">Some content 2</div>
Here is jQuery for those that could use this:
function hideTarget(elem){
$(elem).hide();
}
function showTarget(elem, target, hideThis){
$(elem).click(function(){
$(target).show();
hideTarget(hideThis);
});
}
showTarget('#reso','#resoList','#menuList');
showTarget('#menus','#menuList','#resoList');
Here is the fiddle.

Hide/show div with click of button

I'm trying to hide/show a div based on the click of a button but I can't get it to work.
Below is my code. I can get the alert to see that I'm getting the right ID from the DOM, but I can't show/hide the div content.
function toggleContent(id) {
var e = document.getElementById(id);
//if(e.style.display == null || e.style.display == "none")
if (e.style.visibility == null || e.style.visibility == "hidden") {
//e.style.display = "block";
e.style.visibility: "visible";
} else {
//e.style.display = "none";
e.style.visibility: "hidden";
}
}
<form>
<button onclick="alertData();">Get Alerts</button>
<button onclick="toggleContent('chart');">Chart</button>
<hr>
<div id="chart" style="visibility: hidden;">
my chart
</div>
</form>
You need to set e.style.visibility using =, not : as you would in a CSS file.
In addition, note that the value null is equivalent to visible, not hidden.
function toggleContent(id) {
var e = document.getElementById(id);
if (e.style.visibility == "hidden") {
e.style.visibility = "visible";
} else {
e.style.visibility = "hidden";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<button onclick="alertData();">Get Alerts</button>
<button onclick="toggleContent('chart');">Chart</button>
<hr>
<div id="chart" style="visibility: hidden;">
my chart
</div>
</form>
function toggleContent(id) {
event.preventDefault();
var e = document.getElementById(id);
e.style.visibility=="hidden" || e.style.visibility=="" ? e.style.visibility="visible": e.style.visibility="hidden";
}
#chart{visibility:hidden;}
<form>
<button onclick="toggleContent('chart');">Chart</button>
<hr>
<div id="chart">
my chart
</div></form>

how do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

Toggle function not working when called

The idea is to make two div appear or disappear based on the click. The CSS display style is set to none.
Any help is appreciated.
<div id="mainOval">
<form id="btns">
<input type="button" value="Timer" id="timerBtn" onclick="displayCont('Timer')"/>
<input type="button" value="Countdown" id="ctDownBtn" onclick="displayCont('Countdown')"/>
</form>
</div>
<div id="Timer">
</div>
<div id="Countdown">
</div>
<script type="text/javascript">
function displayCont(inp)
{
var ele = document.getElementById(inp);
var shown = ele.style.display;
if (shown == 'none')
{
ele.style.display = 'block';
}
else if (shown == 'block')
{
ele.style.display = 'none';
}
}
</script>
The correct code is:
if (shown == 'none') {
ele.style.display = 'block';
}
else if (shown == 'block'){
ele.style.display = 'none';
}
You have ot set the style of the element, not just assign a Javascript variable. And equality is ==, not = =.

Categories