I am looking for a way to avoid rewriting the same code again and again.
I am making a web page that has divs with hide and show option, with the help of a button you toggle between hide and show. I found an easy way to achieve the effect with this code:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<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>
This works perfectly but gets a bit tedious when you have a dozen or more divs with said effect. Is there a way to avoid having to rewrite the function for each and every div?
Thank you! :)
Easy, parameterize the id:
function myFunction(divId) {
var x = document.getElementById(divId);
and in the HTML pass the id to the function:
<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV"> ...</div>
<button onclick="myFunction('myOtherDIV')">Try it</button>
<div id="myOtherDIV"> ...</div>
... and so on ...
You can keep one single function and handle as many divs as you want.
You could run the javascript function with a parameter. So you only have one function and then you only need to change the parameter name. See the example below.
function myFunction(div) {
var x = document.getElementById(div);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction('myDIV')">Try it</button>
<button onclick="myFunction('myDIV2')">Try it2</button>
<div id="myDIV">
This is my DIV element.
</div>
<div id="myDIV2">
This is my DIV2 element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
Just pass the div id to a function
function toggleDiv(divId) {
var x = document.getElementById(divId);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
This works perfectly but gets a bit tedious when you have a dozen or
more divs with said effect
Create an array of such div ids to be toggled and iterate the same, for example
var divIds = ["myDIV1", "myDIV2", "myDIV3"];
divIds.forEach( s => toggleDiv(s) );
Pass a parameter into the function.
function myFunction(divName) {
var x = document.getElementById(divName);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<button onclick="myFunction('myDIV2')">Try it</button>
<div id="myDIV2">
This is my DIV2 element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
using event target and operating relatively on elements, can do the task.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<hr>
<div class="wrapper">
<button onclick="myFunction(event)">Try first</button>
<div class="content">
This is my DIV element.
</div>
</div>
<hr>
<div class="wrapper">
<button onclick="myFunction(event)">Try second</button>
<div class="content">
This is my DIV element.
</div>
</div>
<hr>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction(event) {
var wrapper = event.target.parentElement;
var content = wrapper.querySelector('.content');
if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
}
</script>
</body>
</html>
function myFunction() {
var x = document.getElementsByClassName("myDIV");
for (let i = 0; i < x.length; i++){
x[i].style.display = x[i].style.display == "none" ? "block" : "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div class="myDIV">
This is my DIV element.
</div>
<div class="myDIV">
This is my DIV element.
</div>
<div class="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>
function toggleVisibility(selector) {
const elements = document.querySelectorAll(selector);
elements.forEach( element => {
const isVisible = element.offsetHeight;
if (isVisible) {
element.setAttribute('hidden', '');
} else {
element.removeAttribute('hidden');
}
});
}
<button onclick="toggleVisibility('#myDIV')">Try it</button>
<button onclick="toggleVisibility('.toggle')">Try it with className</button>
<div id="myDIV">
This is my DIV element.
</div>
<div class="toggle">
This is my DIV element.
</div>
<div class="toggle">
This is my DIV element.
</div>
Related
I have a simple function when I click on a button to display text for the button, everything is ok but on the first click it's not working then after the second click it's working perfectly can anybody tell me whats my mistake? I have the element hidden in CSS display;none, here is my logic
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#myDIV {
display: none;
}
<button type="button" class="btn btn-primary btn-lg btn-block" onclick="myFunction()">
<div id="myDIV">
This is my DIV element.
</div>
The problem is probably that you didn't close the button tag. So it doesn't find myFunction(). You also need to fetch the computed value of display style not the elements value because css files do not affect the elements styles directly. (e.g. vs style="")
<body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (getComputedStyle(x).display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<button
type="button"
class="btn btn-primary btn-lg btn-block"
onclick="myFunction()"
>
test
</button>
<div id="myDIV">
This is my DIV element.
</div>
</body>
This question already has answers here:
How can I hide/show a div when a button is clicked?
(9 answers)
Closed 2 years ago.
Please can someone explain this situation?
I want to use the same function (hide/show) for more buttons. How can I call the same function with different buttons?
I found how to do it with one but can't find any solution for 2 or more buttons.
I would like to hide div1 if I click on bt1 and hide div2 if I click on bt2. Thank you for any help...
My current code is:
function myFunction() {
var x = document.getElementById("div1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction()">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction()">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
Thank you for your help...
You could pass the ID of the div to your function as a parameter:
function myFunction(el) {
var x = document.getElementById(el);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button id="bt1" onclick="myFunction('div1')">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction('div2')">Button 2</button>
<div id="div2">div2</div>
One way is to pass the ID of the DIV as a function parameter.
function myFunction(id) {
var x = document.getElementById(id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction('div1')">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction('div2')">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
Another way is to pass the button itself, and use DOM navigation, if the DIV to hide and show is always right after the button.
function myFunction(button) {
var x = button.nextElementSibling;
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<html>
<body>
<button id="bt1" onclick="myFunction(this)">Button 1</button>
<div id="div1">div1</div>
<p></p>
<button id="bt2" onclick="myFunction(this)">Button 2</button>
<div id="div2">div2</div>
</body>
</html>
I would do it like so:
Add a data-attribute like data-js-hide="div1"
Add a click event listener for all those elements having the attribute data-js-hide
when clicked use the value "div1" from the attribute data-js-hide
The advantages are that it does not matter where in DOM the elements are. You just need to set the attribute with id, and then on click the item with the id will be hidden or shown accordingly.
function myFunction(event) {
var x = document.getElementById(event.target.dataset.jsHide);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
var buttons = document.querySelectorAll('[data-js-hide]');
buttons.forEach(
button => {
button.addEventListener('click', myFunction);
}
);
<html>
<body>
<button data-js-hide="div1" >Button 1</button>
<div id="div1">div1</div>
<p></p>
<button data-js-hide="div2">Button 2</button>
<div id="div2">div2</div>
<p></p>
<button data-js-hide="div3">Button 3</button>
<div id="div3">div3</div>
</body>
</html>
I have the following code. By default it shows, but I want to hide it by default.
Also, I'm unable to control both of the divs, only 1 of the show/hide toggles work, I want for them (but have been unsuccessful) both to work.
How can I hide by default and expand on click?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</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>
<br><br>
<button onclick="myFunction()">Try it 2</button>
<div id="myDIV2">
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>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
You are overwriting your x variable.
Assign myDIV2 to another variable like y and repeat the process.
Better would be to just assign the same class instead of id to the elements you want to hide and just toggle the class instead of trying to get each element by id.
https://ultimatecourses.com/blog/javascript-hasclass-addclass-removeclass-toggleclass
Just separate the function on the first and scond button
function myFunction_1() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction_2() {
var y = document.getElementById("myDIV2");
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2">
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>
I have two div's with different content. I managed to add show-hide div function when clicking on a button. The problem is, when one div is visible and I click on the second button, they are both visible. I would like to show only one div at a time - while one div is shown and I click on another button, the previous div should hide automatically.
I would not want to use jQuery, hope it's possible with pure JavaScript only.
function horTxtFunction() {
var x = document.getElementById("horTxt");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function verTxtFunction() {
var x = document.getElementById("verTxt");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="horTxtFunction()">Horisontaalne tekstiga</button>
<button onclick="verTxtFunction()">Vertikaalne tekstiga</button>
<div id="horTxt" style="display:none;">
<p>Some content here</p>
</div>
<div id="verTxt" style="display:none;">
<p>Some different content here</p>
</div>
Consider wrapping the two <div> tags in a controller <div> tag and then using "state" to control which child <div> will show.
In the example below I am using the attribute dir to hold the state and the CSS to play off the state and the children <div> classes.
var holder = document.querySelector("[dir]");
function horTxtFunction() {
holder.setAttribute('dir', 'hor');
}
function verTxtFunction() {
holder.setAttribute('dir', 'ver');
}
[dir="ver"] > :not(.verTxt),
[dir="hor"] > :not(.horTxt) {
display: none;
}
<button onclick="horTxtFunction()">Horisontaalne tekstiga</button>
<button onclick="verTxtFunction()">Vertikaalne tekstiga</button>
<div dir="hor">
<div class="horTxt">
<p>Some content here</p>
</div>
<div class="verTxt">
<p>Some different content here</p>
</div>
</div>
The major benefit of doing it this way is if you need to add additional children:
var holder = document.querySelector("[dir]");
function toggle(val) {
holder.setAttribute('dir', val);
}
[dir="ver"] > :not(.verTxt),
[dir="hor"] > :not(.horTxt),
[dir="left"] > :not(.leftTxt),
[dir="right"] > :not(.rightTxt) {
display: none;
}
<button onclick="toggle('hor')">Horizontal</button>
<button onclick="toggle('ver')">Vertical</button>
<button onclick="toggle('left')">Left</button>
<button onclick="toggle('right')">Right</button>
<div dir="hor">
<div class="horTxt">
<p>Some content here</p>
</div>
<div class="verTxt">
<p>Some different content here</p>
</div>
<div class="leftTxt">
<p>This is the left text area</p>
</div>
<div class="rightTxt">
<p>This is the right text area</p>
</div>
</div>
Here I change to a single event handler and pass in the section I want to show. Then I had to extend the CSS to handle the new <div> tags. But now growing to more children is just adding the buttons, divs and CSS.
UPDATE
To hide all <div> tags first I made a minor change:
var holder = document.querySelector(".holder");
function toggle(val) {
holder.setAttribute('dir', val);
}
.holder > div {
display: none;
}
[dir=ver] > .verTxt,
[dir=hor] > .horTxt,
[dir=left] > .leftTxt,
[dir=right] > .rightTxt {
display: block;
}
<button onclick="toggle('hor')">Horizontal</button>
<button onclick="toggle('ver')">Vertical</button>
<button onclick="toggle('left')">Left</button>
<button onclick="toggle('right')">Right</button>
<div class="holder">
<div class="horTxt">
<p>Some content here</p>
</div>
<div class="verTxt">
<p>Some different content here</p>
</div>
<div class="leftTxt">
<p>This is the left text area</p>
</div>
<div class="rightTxt">
<p>This is the right text area</p>
</div>
</div>
This hides all of the internal <div> tags and then only shows the correct one based on the value of the dir attribute. Since there is no dir attribute to start then no internal <div>s will show.
You need to make sure to hide the other div and not just show the other.
function horTxtFunction() {
var x = document.getElementById("horTxt");
var otherDiv = document.getElementById("verTxt");
if (x.style.display === "none") {
x.style.display = "block";
overDiv.style.display = "none";
} else {
x.style.display = "none";
overDiv.style.display = "block";
}
}
I`m begginer in Javascript and I need some help.
So, I need that, when I push the button, paragraph "leftside" appear
<div id="content">
<script>
function myFunction() {
document.getElementById("contentp").innerHTML = leftside;
var x = document.getElementById("leftside")
x.style.display = "normal";
}
</script>
<button id="buttonI" type="button" onclick="myFunction()">Show left side!</button>
<p id="leftside" style="display: none">Left side</p>
<p id="contentp"></p>
x.style.display = "block";
set it block or another value of display except none
You have to append the leftside to the contentp and set its display property to block. normal is not a valid option
<script>
function myFunction() {
document.getElementById("contentp").appendChild(document.getElementById("leftside"));
document.getElementById("leftside").style.display = "block";
}
</script>
<button id="buttonI" type="button" onclick="myFunction()">Show left side!</button>
<p id="leftside" style="display: none">Left side</p>
<p id="contentp"></p>