Dynamic way to hide divs vanilla javascript - javascript

Is there a more dynamic way to hide/show divs that are identical in structure with no identifiers?
Click to show
I'm some stuff
<div class="setup" onclick="show(1)">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
function show(elem) {
var p = document.getElementsByClassName("hidden");
if (p[elem] != undefined) {
if (p[elem].style.display == "none") {
p[elem].style.display = "block";
} else {
p[elem].style.display = "none";
}
}
}
http://jsfiddle.net/ba7yfmz6/29/

Use this:
<div class="setup" onclick="show(this)">
JavaScript:
function show(elem) {
var paragraph = elem.querySelector(".hidden");
if (paragraph.style.display == "none") {
paragraph.style.display = "block";
} else {
paragraph.style.display = "none";
}
Hopefully this helps!

Yes, there is a way!
You can get all your elements, iterate them via forEach and assign your function to their onclick property:
document.querySelectorAll('.setup').forEach(div => {
div.onclick = showElem;
});
Doing this, you can get rid of the onlick on your HTML elements.
To get their child element (the one you want to hide / show, obviously), your show() function can look like this:
function show() {
const hidden = this.getElementsByClassName('hidden')[0];
if (hidden.style.display == 'none') {
hidden.style.display = 'block';
} else {
hidden.style.display = 'none';
}
}
And all together:
document.querySelectorAll('.setup').forEach(div => {
div.onclick = show;
});
function show() {
const hidden = this.getElementsByClassName('hidden')[0];
if (hidden.style.display == 'none') {
hidden.style.display = 'block';
} else {
hidden.style.display = 'none';
}
}
.setup {
border-top: solid #ccc 3px;
border-bottom: solid #ccc 3px;
margin-bottom: 5%;
}
.setup:hover {
cursor: pointer;
}
.hidden {
text-align: center;
font-weight: bold;
border-top: solid black 3px;
border-bottom: solid black 3px;
background-color: yellow;
display: none;
}
<div class="setup">
Click to show
<p class="hidden">
I'm some stuff
</p>
</div>
<div class="setup">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>
JS Fiddle: http://jsfiddle.net/ba7yfmz6/38/
More info:
forEach
querySelectorAll()

You can use this.
Also, since the div doesn't have a style attribute, checking for style.display === 'none' would always be false on the first click; it would set the the style.display to none. Checking for the computed style would show the hidden element on first click.
function show(el) {
const toggle = el.querySelector('.hidden');
toggle.style.display = window.getComputedStyle(toggle).display === 'none' ? 'block' : 'none';
}
.setup {
border-top: solid #ccc 3px;
border-bottom: solid #ccc 3px;
margin-bottom: 5%;
}
.setup:hover {
cursor: pointer;
}
.hidden {
text-align: center;
font-weight: bold;
border-top: solid black 3px;
border-bottom: solid black 3px;
background-color: yellow;
display: none;
}
<div class="setup" onclick="show(this)">
Click to show
<p class="hidden">
I'm some stuff
</p>
</div>
<div class="setup" onclick="show(this)">
Click to show
<p class="hidden">
I'm more stuff
</p>
</div>

<div class="setup" onclick="show(this)">
Then the JavaScript:
function show(that) {
var hiddenElements = that.getElementsByClassName('hidden');
for (var i = 0; i < hiddenElements.length; i++) {
var style = hiddenElements[i].style;
style.display = style.display == "block" ? "none" : "block";
}
}

Related

I need an auto hide function to use on a website (Java Script)

I'm new to coding, but looking at doing a bootcamp to help me learn some more, however, at the moment I am having some trouble getting some code to do what I need it to.
The following code is what I use on the website I'm working on:
<button class="zerobut" onclick="myFunction5()">Open</button>
<script>
function myFunction5() {
var x = document.getElementById("product5");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
What I need is an automatic hide once a different button is clicked. There are 5 different categories from which a customer must choose before the options are displayed, but at the moment it doesn't close the previous option unless you click on the button again.
Is anyone able to help me understand what I need to change to make this happen? (sorry if I'm explaining this poorly.)
Here's another section's code. So when this one opens, the first one should close automatically if possible.
`
<button class="healthbut" onclick="myFunction3()">Open2</button>
<script>
function myFunction3() {
var x = document.getElementById("product3");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
`
It doesn't work the first time because the style.display attribute is initially set to the empty string. If you add the style attribute it works.
function myFunction5() {
var x = document.getElementById("product5");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
.products {
background-color:yellow;
border: 1px solid black;
padding:1rem;
}
<button class="zerobut" onclick="myFunction5()">Open/Close</button>
<div class = 'products' style='display:block' id='product5'>Product 5 panel</div>
A better option is to just check to see if your style.display attribute is not 'none' and change it otherwise as below
function myFunction5() {
var x = document.getElementById("product5");
if (x.style.display !== "none") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
.products {
background-color: yellow;
border: 1px solid black;
padding: 1rem;
}
<button class="zerobut" onclick="myFunction5()">Open/Close</button>
<div class='products' id='product5'>Product 5 panel</div>
Finally, an even better way to do it is to create a 'hide' class and toggle the class element
function myFunction5() {
var x = document.getElementById("product5");
x.classList.toggle('hide');
}
.products {
background-color:yellow;
border: 1px solid black;
padding:1rem;
}
.products.hide {
display: none;
}
<button class="zerobut" onclick="myFunction5()">Open/Close</button>
<div class = 'products' id='product5'>Product 5 panel</div>
Finally, if you've got some panels you need to hide when you're displaying others, then this can be done as follows:
productNumber = 1;
totalNumberOfProducts = 5;
function myFunction5() {
//Select all elements with the class 'products'.
const elements = document.querySelectorAll(".products");
//choose the next element to display
productNumber++;
//If we get past the last element then go back to the one with id 'product1'
if (productNumber > totalNumberOfProducts) {
productNumber = 1;
}
//Loop through each element and hide all elements except the one that's got the id of
//"product"+productNumber;
elements.forEach((element) => {
const elementId = element.getAttribute('id');
if (elementId == 'product' + productNumber) {
element.classList.remove('hide');
} else {
element.classList.add('hide');
}
});
}
.products {
border: 1px solid black;
padding: 1rem;
}
#product1 {
background-color: brown;
}
#product2 {
background-color: salmon;
}
#product3 {
background-color: pink;
}
#product4 {
background-color: skyblue;
}
#product5 {
background-color: yellow;
}
.products.hide {
display: none;
}
<button class="zerobut" onclick="myFunction5()">Go to next panel</button>
<div class='products' id='product1'>Product 1 panel</div>
<div class='products hide' id='product2'>Product 2 panel</div>
<div class='products hide' id='product3'>Product 3 panel</div>
<div class='products hide' id='product4'>Product 4 panel</div>
<div class='products hide' id='product5'>Product 5 panel</div>

How to set initial state of div element to hide

I created a simple function which shows or hides a div tag on clicking a button but how can i set it to initially be hiding and after clicking the button it is displayed?
Just set it's display style property to None.
element = document.getElementById('toggle');
button = document.getElementById('toggle-button');
function hideAndShow(){
if(element.style.display == 'none'|| element.style.display == '') // checks if the display property is set to none or not
{
element.style.display = 'Block'; // if set to none then set the display property to block
button.innerHTML = 'Hide'; // changes the button's text
}
else{
element.style.display = 'None'; // otherwise set it to none
button.innerHTML = 'Show';
}
}
#toggle{
width: 100%;
margin: auto;
height: 50px;
display: None; /*this set's the divison to a hidden state by default*/
background-color: rgba(248,25,34,0.8);
}
#toggle-button{
width: 100%;
margin: 5px;
height: 25px;
padding: 5px;
color: rgba(25,25,67,0.5);
}
<div id='toggle'></div>
<button id='toggle-button' onclick='hideAndShow()'>Show</button>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
};
function toggle() {
document.getElementById('test').style.display = 'block';
}
.hide {
display: none;
}
<div id="test" class="hide">Test</div>
<button onclick="toggle()">Toggle</button>
function btnClick(){
const divElement = document.getElementById('myDiv');
if (divElement.classList.contains("show")) {
divElement.classList.remove("show")
divElement.classList.add("hide")
} else {
divElement.classList.add("show")
divElement.classList.remove("hide")
}
}
.hide{
display: none
}
.show{
display: block
}
<div id="myDiv" class="hide">
Hello, I am Div HTML Content
</div>
<button onclick="btnClick()">Click Me!!</button>

How to chain javascript hide/show function for each div ID?

I have many <p>s with the same function.
document.getElementById("minus").onclick = function() {
functionHide()
};
function functionHide() {
document.getElementById("plus").style.display = "block";
document.getElementById("minus").style.display = "none";
}
document.getElementById("plus").onclick = function() {
functionShow()
};
function functionShow() {
document.getElementById("plus").style.display = "none";
document.getElementById("minus").style.display = "block";
}
#plus {
display: none;
cursor: pointer;
}
#minus {
cursor: pointer;
}
.floatright {
float: right
}
.w50 {
width: 50%;
text-align: center;
}
<div class="w50">
<p>What paperwork do I need to complete to file for divorce ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
<p>How do I change my custody and suport orders ?
<span class="floatright inlineb" id="minus">- </span>
<span class="floatright inlineb" id="plus">+</span>
</p>
</div>
When I click on the first minus ( "-" ) it works correctly.
but for the second, it doesn't work.
I want to know how can I automatically chain for all others divs. they have the same typing code.
Also, I would know how can I change the last element (" - ") when an another + is clicked?
Here is a preview of what I want to do
And a fiddle: https://jsfiddle.net/khrismuc/prsebqg3/15/
You are using duplicate IDs, which is a no-no. Here is an example using classes and .querySelectorAll.
var minuses = document.querySelectorAll(".minus");
var pluses = document.querySelectorAll(".plus");
minuses.forEach(function(minus) {
minus.addEventListener('click', functionHide);
});
pluses.forEach(function(plus) {
plus.addEventListener('click', functionShow);
});
function functionHide() {
pluses.forEach(function(plus) {
plus.style.display = "block";
});
minuses.forEach(function(minus) {
minus.style.display = "none";
});
}
function functionShow() {
pluses.forEach(function(plus) {
plus.style.display = "none";
});
minuses.forEach(function(minus) {
minus.style.display = "block";
});
}
You can modify for your particular uses.
Your logic needs to be slightly more complex:
var current = -1;
function handleClick(clicked) {
$(".w50 p").removeClass("active").find("span").text("+");
$("#box p").hide();
if (current === clicked) {
current = -1;
return;
}
current = clicked;
$(".w50 p").eq(current).addClass("active").find("span").text("-");
$("#box p").eq(current).show();
}
$(document).ready(function() {
$(".w50 p").each(function(i, el) {
$(this).append($("<span>").text("+"));
$(this).click(function() {
handleClick(i);
});
});
$(".w50 p").eq(0).click();
});
.w50 {
width: 80%;
text-align: center;
}
.w50 p {
cursor: pointer
}
.w50 p.active {
color: orange
}
.w50 p span {
float: right;
width: 1em;
display: inline-block;
}
#box {
background-color: orange;
margin: 20px;
min-height: 6em;
}
#box p {
display: none;
padding: 1em
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w50">
<p>What paperwork do I need to complete to file for divorce?</p>
<p>How do I change my custody and support orders?</p>
</div>
<div id="box">
<p>Paperwork description</p>
<p>Custody description</p>
</div>

Javascript Methods

I am trying to create a toggle function with JavaScript (not jQuery).
I have created an ID named box, and a class within the ID named box-open.
The width of the ID box is 100px.
The width of box-open is set to 1000px.
When I try to use my code I get this error, that displays “Cannot set property 'display' of undefined”.
I have tried writing the code a couple of different ways, but I always seem to get the same error in the console.
function toggle(open) {
box = document.getElementById('box').style.display = 'block';
if (open == true) {
box.style.display = 'none';
boxOpen = document.getElementsByClassName('box-open').style.display = 'block';
} else {
box.style.display = 'block';
boxOpen.style.display = 'none';
}
}
#box {
width: 100px;
height: 100px;
background: gold;
text-align: center;
display: block;
}
.box-open {
width: 50px;
height: 50px;
background: green;
display: none;
}
<div id="box" class="box-close"></div>
<button type="button" onClick="toggle()">click me</button>
This is a link to my codepen, where you can find the code
http://codepen.io/2bu/pen/YNYjjR
I am not sure but this line:
box = document.getElementById('box').style.display = 'block'
should be maybe
box = document.getElementById('box');
Your function is not very flexible because it can only toggle a specific box with ID "box". Instead you could pass in a selector for the element you want to toggle:
<div id="box" class="box-close"></div>
<button type="button" onClick="toggle('#box')">click me</button>
And then in your Javascript:
function toggle(selector) {
var box = document.querySelector(selector);
var isOpen = box.style.display === "block";
box.style.display = isOpen ? "none" : "block";
}
This way you can use the same toggle function to toggle any box you like.
Here is a simple jQuery implementation. Just change the .box-toggled class to be whatever you actually want. It also uses eventListener to keep your HTML cleaner.
https://jsfiddle.net/segbxnh3/3/
var box = document.querySelector('#box');
var toggleButton = document.querySelector('button');
toggleButton.addEventListener('click', function() {
$(box).toggleClass('box-toggled');
});
UPDATE:
Here is a vanilla JS implementation.
https://jsfiddle.net/segbxnh3/5/
var box = document.querySelector('#box');
var toggleButton = document.querySelector('button');
toggleButton.addEventListener('click', function() {
if (box.classList.contains('box-toggled')) {
box.classList.remove('box-toggled');
} else {
box.classList.add('box-toggled');
}
});
You can use like this.
function toggle(open, element){
box = document.getElementById('box');
boxOpen = document.getElementById('box-open');
if ( open == true) {
box.style.display = 'none';
boxOpen.style.display = 'block';
element.setAttribute('onclick', "toggle(false, this);");
}else{
box.style.display = 'block';
boxOpen.style.display = 'none';
element.setAttribute('onclick', "toggle(true, this);");
}
}
*{
margin:0px;
padding:0px;
font-family: 'Montserrat', sans-serif;
}
#box{
width:100px;
height: 100px;
background: gold;
text-align: center;
display:block;
}
#box-open{
width:50px;
height: 50px;
background: green;
display: none;
}
<div id="box"></div>
<div id="box-open"></div>
<button type="button" onClick="toggle(true, this);" >click me </button>
Also, check this solution

Hide popup window if click out his area [duplicate]

I want to make a popup that should appear once a button is clicked and disappear once the user clicks outside of the box.
I'm not sure how to make the div disappear when I click outside of it.
var popbox = document.getElementById("popbox");
document.getElementById("linkbox").onclick = function () {
popbox.style.display = "block";
};
???.onclick = function () {
popbox.style.display = "none";
};
Here is the second version which has a transparent overlay as asked by the asker in the comments...
window.onload = function(){
var popup = document.getElementById('popup');
var overlay = document.getElementById('backgroundOverlay');
var openButton = document.getElementById('openOverlay');
document.onclick = function(e){
if(e.target.id == 'backgroundOverlay'){
popup.style.display = 'none';
overlay.style.display = 'none';
}
if(e.target === openButton){
popup.style.display = 'block';
overlay.style.display = 'block';
}
};
};
#backgroundOverlay{
background-color:transparent;
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
display:block;
}
#popup{
background-color:#fff;
border:1px solid #000;
width:80vw;
height:80vh;
position:absolute;
margin-left:10vw;
margin-right:10vw;
margin-top:10vh;
margin-bottom:10vh;
z-index:500;
}
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div>
<div id="backgroundOverlay"></div>
<input type="button" id="openOverlay" value="open popup">
Here is the first version...
Here is some code. If there is anything else to add, please let me know :)
The event (e) object gives access to information about the event. e.target gives you the element that triggered the event.
window.onload = function(){
var divToHide = document.getElementById('divToHide');
document.onclick = function(e){
if(e.target.id !== 'divToHide'){
//element clicked wasn't the div; hide the div
divToHide.style.display = 'none';
}
};
};
<div id="divToHide">Click outside of this div to hide it.</div>
Here, the idea is to detect click events on the page and set the container’s display to none only when the target of the click isn’t one of the div descendants.
HTML
<div id="container">
<label>Enter your name:</label>
<input type="text">
<button id="submit">Submit</button>
</div>
JS
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('container');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
This is code I use to close my side bar when click outside
function openNav() {
document.getElementById("mySidebar").style.width = "100px";
document.getElementById("curtain_menu").style.marginLeft = "100px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("curtain_menu").style.marginLeft = "0";
}
document.onclick = function (e) {
if (e.target.id !== 'mySidebar' && e.target.id !== 'btn_frontpage_menu') {
if (e.target.offsetParent && e.target.offsetParent.id !== 'mySidebar')
closeNav()
}
}
.sidebar {
font-family: sans-serif;
height: 50%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
opacity: 0.9;
}
.sidebar a,
.dropdown-btn {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 1vw !important;
color: rgb(195, 195, 195);
display: block;
background: none;
width: 100%;
text-align: left;
cursor: pointer;
outline: none;
transition: 0.3s;
border: none;
}
.dropdown-container a {
color: rgb(174, 174, 174) !important;
}
.sidebar a:hover,
.dropdown-btn:hover,
.dropdown-container a:hover {
color: green !important;
/* background-color: #5c5c5c; */
}
.sidebar .closebtn {
position: absolute;
top: 12px;
font-size: 36px !important;
margin-right: 5px;
text-align: right;
right: 20px;
}
.openbtn {
font-size: 20px !important;
cursor: pointer;
background-color: transparent;
color: black;
padding: 6px 15px;
border: none;
float: left;
}
#main {
position :absolute;
width: 100%;
height: 100%;
left: 100px
}
<div id="mySidebar" class="sidebar" style="width: 100px;">
<a href="javascript:void(0)" class="closebtn"
onclick="closeNav()">×</a>
Home
<div class="dropdown-container">
Job Management
Request
Pending
</div>
</div>
<div id="curtain_menu">
<button id="btn_frontpage_menu" class="openbtn" onclick="openNav()">☰</button>
<div id="datetime"></div>
</div>
<div id="main"> Outside of 'Side Bar' is here
</div>
Here is my Solution.
yourFunc=e=>{
var popbox = document.getElementById("popbox");
if(e.target.id !=="popbox"){
popbox.style.display = "none";
}else{
popbox.style.display = "block";
}
}
document.addEventListener("click",yourFunc)
hope this will work for you
<script>
// Get the element
var modal = document.getElementById('modal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
This code is tested and it's working nicely, thank you.
Could be done with onblur event.
// required for focus
divEl.setAttribute('tabindex', '1');
divEl.onblur = event => {
// hide only if blur occurred outside divEl, ignore its children
if (!event.currentTarget.contains(event.relatedTarget)) {
hide();
}
// re-focus, if a child took it
divEl.focus();
};
divEl.focus();
P.S. For IE11 a small hack event.relatedTarget = event.relatedTarget || document.activeElement; could be required.
<div class='icon alk-icon-close'>hidden hire</div>
document.addEventListener('click', function(e) {
var target = e.target.classList.value
if (target == 'icon alk-icon-close') ) {
hidden hire
}
});
plug this in
(function(){
// click outside of element to hide it
let hels = [];
window.hidable = (el, excepter, hider) => {
// hider takes el as the only arg
hels.push([el, excepter, hider]);
return el;
}
window.addEventListener('click', e=>{
for(let i = 0; i < hels.length; i++){
let el = hels[i][0];
let excepter = hels[i][1];
let hider = hels[i][2];
if(!el.contains(e.target) && excepter !== e.target){
hider(el);
}
}
});
})()
unit test
/* excepter is the element to trigger panel show */
// example implementation
window.hidable(panel_el, show_panel_button, el=>el.remove());
// other hiders can be:
el=>el.style.display = 'none';
// depends on your show implementation
el.onmouseleave = function(){
document.body.onclick = function(){
el.style.display = 'none';
document.body.onclick = null;
}
}
Okay, here's a jQuery based solution based on any div clicked within the DOM.
$('div').on('click', function(e){
var parents = $(e.currentTarget).parents();
for (var i = 0; i < parents.length; i++) {
if (parents[i].id === 'divToHide' || e.currentTarget.id === 'divToHide') {
// you are in the popup
};
}
e.stopPropagation();
});
This looks at your current element, as well as any of the parents, and checks if the id matches up. If divToHide is in the parents() list, then you keep the popup open.
*NOTE: This requires wrapping your content within a wrapper div or something similar.

Categories