Javascript: Hiding and Showing Div Tag with a Toggle Button

toggle show/hide div with button?

Look at jQuery Toggle

HTML:

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

jQuery:

jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});

For versions of jQuery 1.7 and newer use

jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});

For reference, kindly check this demo

How to show/hide div with toggle in different page

I copied what you wrote in your original code in jsfiddle using the same css I found there. Then I just rewrote the javascript part.

What it does is attaching a change event handler to any checkbox found on the page so that when their state it's changed, the corresponding label gets shown or hidden. The corresponding label is found using the checkbox id with the prefix label-.

In that event, the state of the checkbox changed gets pushed in the localStorage. At the very beginning, the page first checks if there's any state saved for each of the checkbox found and in case there is, its state gets updated correspondingly.

In Firefox localStorage methods (getItem/setItem) return SecurityError: The operation is insecure. I could run that code on a dedicated html page to verify it's working correctly (on Chrome for sure). So to avoid any problem at first, I added a securityFlag on top of the js code. When that flag is set to true, the localStorage won't be engaged at all so that you could see the preview here with no errors.

//if set to true, any operation involving localStorage will be excluded
let securityFlag = true;

/**
* Initialize the Checkboxes state according to what's stored on localStorage
*/
function initCheckboxStateBasedOnLocalStorage(){
//for each of the checkboxes on the page
document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {

//if securityFlag is true, skip the operation
if(securityFlag) return;

//retrieves the value stored in localStorage paired to the id passed
let valueStored = window.localStorage.getItem(checkbox.id);
//if valueStored is set
if(valueStored == 'true' || valueStored == 'false')
//sets the checkbox value with what was retrieved from localStorage
checkbox.checked = valueStored == 'true' ? true : false;
});
}

/**
* Will hide/show the label corresponding to checkbox and will save its value on localStorage
* It will be registered as the handler of the change event of every checkbox in the page
*/
function onCheckBoxStateChange(){

let checkbox = event.target;

//guesses the id of the label dedicated to the checkbox triggering the event
let msgContainer = document.getElementById(`label-${checkbox.id}`);
//if this checkbox is checked,
if (checkbox.checked){
//show the corresponding label
msgContainer.style.display = "block";
//if securityFlag is true, skip the operation
if(securityFlag) return;
//sets the state in localStorage for this.id
window.localStorage.setItem(checkbox.id ,true);
}
//otherwise
else{
//hide the corresponding label
msgContainer.style.display = "none";
//if securityFlag is true, skip the operation
if(securityFlag) return;
//sets the state in localStorage for this.id
window.localStorage.setItem(checkbox.id ,false);
}
}

//When the document has been loaded
document.addEventListener("DOMContentLoaded", function() {
//for each of the checkboxes on the page
document.querySelectorAll('input[type="checkbox"]').forEach( (checkbox, i) => {
//attach an handler to the event change
checkbox.addEventListener("change", onCheckBoxStateChange );
});
});

//reflect the value of checkboxed according to what's stored on localStorage
initCheckboxStateBasedOnLocalStorage();
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}

.switch input {
opacity: 0;
width: 0;
height: 0;
}

.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}

input:checked + .slider {
background-color: #2196F3;
}

input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
border-radius: 34px;
}

.slider.round:before {
border-radius: 50%;
}

/*END OF TOGGLE SWITCH*/

.hideme {
padding:20px;
background: blue;
color: white;
font-weight: 800;
text-align: center;
}
<p>checkbox1</p>
<label class="switch">
<input type="checkbox" id="ck1">
<span class="slider round hide-off"></span>
</label>

<br><br>

<p>checkbox2</p>
<label class="switch">
<input type="checkbox" id="ck2">
<span class="slider round hide-off"></span>
</label>
<br><br>

<div class="hideme" id="label-ck1">Label bound to checkbox1</div>
<div class="hideme" id="label-ck2">Label bound to checkbox2</div>

Button show/hide div in javascript, toggle not working

Turns out I didn't understand the question properly. The problem is, you're removing the show class from all the content divs in the remove() function. Then you're adding the show class again to the corresponding content div which doesn't actually toggle the content.

Simple fix. Inside the remove() function, only remove the show class if the div already has it. here's a fiddle
https://jsfiddle.net/sap4bn8d/

Update
We forgot to ingore to remove the show class if the corresponding content is already shown. Here's the fix:
https://jsfiddle.net/sap4bn8d/1/

Hide / Show toggle button doesn't start with content hidden

add style display none to your div id moreDetails

<div id="moreDetails" style="display: none">

or you can use like this also

<script>
function toggle(){
let Text = document.getElementById('moreDetails');

if(Text.style.display == "none"){
Text.style.display= "block";
}
else {
Text.style.display = "none";
}
}
document.getElementById("moreDetails").style.display = "none";

</script>

or you can use
ternary operator

<script>
function toggle(){
const Text = document.getElementById('moreDetails');
Text.style.display = Text.style.display == "none" ? "block" : "none";
}
document.getElementById("moreDetails").style.display = "none";
</script>

javascript toggle showing and hiding several div elements

It can be done by setting the div id's in the anchor tag's href attribute, and showing the corresponding div while hiding the rest. It can be done for any number of div's with no extra script, Just add the new div id to the new anchor tags href. You should give a common class to all the div's like month to select them all.

$("a.btn").click(function() {  var id = $(this).attr("href");  $("div.month:visible").hide();  $(id).show();});
.hidden {  display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="#MAY" class="btn" id="button-may">MAY</a><a href="#JUNE" class="btn" id="button-june">JUNE</a><!-- first div, shows on page load --><div id="MAY" class="month">  <div style="background-color: lightgrey">    <h1 style="padding: 5px"><strong>May 2017</strong></h1>  </div></div><!-- second div, hidden originally --><div class="month hidden" id="JUNE">  <div style="background-color: lightgrey">    <h1 style="padding: 5px"><strong>June 2017</strong></h1>  </div></div>

How to set the toggle of a div element to be first hidden and only after clicked shown?

I would recommend you to use getComputedStyle() rather than your current approach of calling .style. As stated on the documentation,

The Window.getComputedStyle() method returns an object containing the
values of all CSS properties of an element, after applying active
stylesheets and resolving any basic computation those values may
contain.

Using .style will not allow you to read CSS defined within an external stylesheet, as it can only read inline style.

And now, to answer your question, you can simply set #myDIV to include the additional CSS property display, and set it to none, such that it is not displayed on load.

myFunction() will only be triggered when the button is clicked, whereby getComputedStyle() will be used to check the CSS properties of #myDIV.

function myFunction() {  var x = document.getElementById("myDIV");  if (window.getComputedStyle(x).display === "none") {    x.style.display = "block";  } else {    x.style.display = "none";  }}
#myDIV {  width: 100%;  padding: 50px 0;  text-align: center;  background-color: lightblue;  margin-top: 20px;  display: none;}
<!DOCTYPE html><html>
<head> <meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body> <p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p> <button onclick="myFunction()">Try it</button> <div id="myDIV"> This is my DIV element. </div> <p><b>Note:</b> The element will not take up any space when the display property set to "none".</p></body>
</html>

Javascript toggle button: change action sequence from show/hide to hide/show

Just use:

if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}

instead of:

if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}

This is your code:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
});
}
.active, .collapsible:hover {
background-color: #8511ae;
color: white; font-weight: bold; text-decoration: underline;
}
.collapsible {
background-color: #faf9d8;
color: #4e3fe3; font-style: italic; font-weight: bold;
font-family: verdana, sans-serif;
cursor: pointer;
padding: 5px;
width: 35%;
float: left
border: 0px solid #8511ae;
text-align: center;
outline: none;
font-size: 15px;
margin-top: 2%;
margin-bottom: 0%;
margin-left: 2%;
margin-right: 24%;
}
.content {
width: 35%;
float: left;
padding: 0px;
border: 0px solid #8511ae;
margin-top: 0%;
margin-bottom: 0%;
margin-left: 2%;
margin-right: 3%;
background-color: #faf9d8;
}
<button type="button" class="collapsible">Toggle document map</button>
<div class="content">
<p>bla..bla</p>
</div>

How to get more toggle hide/show div with different class

I believe you can have more dynamism by making better use of css selectors and adding an attribute with the same input id to the divs you intend to show/hide.

HTML:

<label class="switch">
<input type="checkbox" id="ck1">
<span class="slider round hide-off"></span>
</label>
<br><br>

<label class="switch">
<input type="checkbox" id="ck2">
<span class="slider round hide-off"></span>
</label>
<br><br>

<div class="hideme" id="label-ck1">Please hide me...</div>
<div class="hideme" id="label-ck2">Please hide me...</div>

JAVASCRIPT

$(document).ready(function(){
getLocalStatus()
$(".switch input").on("change", function(e) {
const element = e.currentTarget;
saveStatus(element)
setLabelVisibility(element.getAttribute('id'),element.checked);
})
})

function getLocalStatus() {
const checkboxes = $('input[type=checkbox]');
checkboxes.each(function(index,checkbox){
const checkboxId = checkbox.getAttribute('id')
var currentStatus= localStorage.getItem(checkboxId)
if (currentStatus == "true") {
currentStatus = true;
} else {
currentStatus = false;
}
checkbox.checked = currentStatus;
setLabelVisibility(checkboxId, currentStatus)
})
}

function setLabelVisibility(id,status){
const label = $("#label-" + id + "");
if(status == false){
label.hide();
return;
}
label.show();
}

function saveStatus(e) {
localStorage.setItem(e.getAttribute('id'), e.checked)
}


Related Topics



Leave a reply



Submit