JavaScript Toggle Display - javascript

I'm trying to use vanilla JavaScript to toggle display: none and display: block on elements with the same class. It mostly works, but for some reason you need to click the button twice for it to work and it's eating away at me. The code and a link to CodePen is below.
The HTML:
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>
<div class="d">d</div>
<button onclick="toggle('a')">Toggle A</button>
<button onclick="toggle('b')">Toggle B</button>
<button onclick="toggle('c')">Toggle C</button>
<button onclick="toggle('d')">Toggle D</button>
The JS:
function toggle(div) {
var divs = document.getElementsByClassName(div);
for(var i = 0; i < divs.length; i++) {
if(divs[i].style.display === "block") {
divs[i].style.display="none";
}
else {
divs[i].style.display="block";
}
}
}
The Demo:
CodePen

add the style attribute to the divs..
<div class="a" style="display:block">a</div>
<div class="b" style="display:block">b</div>
<div class="c" style="display:block">c</div>
<div class="d" style="display:block">d</div>

I would do this instead:
<div class='a'>a</div>
<div class='b'>b</div>
<div class='c'>c</div>
<div class='d'>d</div>
<input type='button' id='aT' value='Toggle A' />
<input type='button' id='bT' value='Toggle B' />
<input type='button' id='cT' value='Toggle C' />
<input type='button' id='dT' value='Toggle D' />
Put external JavaScript tag in <head> for caching:
var pre = onload;
onload = function(){
if(pre)pre();
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
function C(n){
if(doc.getElementsByClassName){
return doc.getElementsByClassName(n);
}
var t = doc.getElementsByTagName('*'), a = [];
for(var i=0,l=t.length; i<l; i++){
if(t[i].className.match(new RegExp('\\b'+n+'\\b'))){
a.push(t[i]);
}
}
return a;
}
function getStyleProp(elem, prop){
return getComputedStyle(elem).getPropertyValue(prop) || elem.currentStyle[prop];
}
function toggle(elem){
elem.style.display = getStyleProp(elem, 'display').match(/^block$/i) ? 'none' : 'block';
return elem;
}
var btns = ['a', 'b', 'c', 'd'];
for(var i=0,l=btns.length; i<l; i++){
(function(i){
var b = btns[i], c = C(b);
E(b+'T').onclick = function(){
for(var n=0,q=c.length; n<q; n++){
toggle(c[n]);
}
}
})(i);
}
}

Add display: block; to the CSS definition for the DIV.

your var divs = document.getElementsByClassName(div); will only return one element because there is only one element with that class.
<div id="blocks'>
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>
<div class="d">d</div>
</div>
function toggle(div) {
var divs = document.getElementById('blocks');
var ele = blocks.getElementsByTagName("div');
var sty = "";
for(var i = 0; i < ele.length; i++) {
sty = ( ele[i].className.indexOf( div ) ) ? 'block' : 'none';
ele[i].style.display = sty;
}
}
}

Related

Cycle through divs up and down with Jquery

I need to cycle up and down through two sets of divs simultaneously. This code works well for cycling up the list (button1) but when I tried to create a down button (button2) it messes up the div order and doesn't cycle correctly. How can I alter this code to make it successfully cycle up and down through the list in the correct order?
$(document).ready(function() {
var divs = $('div[id^="num-"]').hide(),
i = 0;
function cycleone() {
divs.hide().eq(i).show();
i = ++i % divs.length;
};
cycleone()
$('#button1').click(function() {
cycleone()
})
});
$(document).ready(function() {
var divsv = $('div[id^="numv-"]').hide(),
iv = 0;
function cycletwo() {
divsv.hide().eq(iv).show();
iv = ++iv % divsv.length;
};
cycletwo()
$('#button1').click(function() {
cycletwo()
})
});
$(document).ready(function() {
var divs = $('div[id^="num-"]').hide(),
i = 0;
function cycleonedown() {
divs.hide().eq(i).show();
i = --i % divs.length;
};
cycleonedown()
$('#button2').click(function() {
cycleonedown()
})
});
$(document).ready(function() {
var divsv = $('div[id^="numv-"]').hide(),
iv = 0;
function cycletwodown() {
divsv.hide().eq(iv).show();
iv = --iv % divsv.length;
};
cycletwodown()
$('#button2').click(function() {
cycletwodown()
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num-1">1</div>
<div id="num-2">2</div>
<div id="num-3">3</div>
<div id="num-4">4</div>
<div id="num-5">5</div>
<div id="num-6">6</div>
<div id="num-7">7</div>
<div id="numv-1">A</div>
<div id="numv-2">B</div>
<div id="numv-3">C</div>
<div id="numv-4">D</div>
<div id="numv-5">E</div>
<div id="numv-6">F</div>
<div id="numv-7">G</div>
<button id="button1">Up</button>
<button id="button2">Down</button>
As i can see you are using jquery, try the snippet below
$(document).ready(function(){
var lettersArray=[];
var step=1;
var lastStep=parseInt($(document).find('.num').length);
if($(document).find('.numv').length){
$(document).find('.numv').each(function(){
var letter=$(this).html();
lettersArray.push(letter);
});
}
showCycle=function(step){
var stepLetter=lettersArray[step-1];
$('#number').html(step);
$('#letter').html(stepLetter);
}
$(document).on('click','#button1',function(){
step=step+1;
step=step > lastStep ? 1 : step;
showCycle(step);
});
$(document).on('click','#button2',function(){
step=step-1;
step=step < 1 ? lastStep : step;
showCycle(step);
});
});
.num, .numv{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div id="num-1"class="num">1</div>
<div id="num-2"class="num">2</div>
<div id="num-3"class="num">3</div>
<div id="num-4"class="num">4</div>
<div id="num-5"class="num">5</div>
<div id="num-6"class="num">6</div>
<div id="num-7"class="num">7</div>
<div id="numv-1"class="numv">A</div>
<div id="numv-2"class="numv">B</div>
<div id="numv-3"class="numv">C</div>
<div id="numv-4"class="numv">D</div>
<div id="numv-5"class="numv">E</div>
<div id="numv-6"class="numv">F</div>
<div id="numv-7"class="numv">G</div>
<div id="number">1</div>
<div id="letter">A</div>
<button id="button1">Up</button>
<button id="button2">Down</button>

onClick event calling function, but not firing

Okay, so I'm getting a weird problem with my onClick elements.
I'm using PHP to echo some code, and here it is:
<div class = \"dropdown\">
<i id = \"elipses_$id\" onClick = \"dropDown_$id()\" style = \"color:#777\" class=\"fas fa-ellipsis-v\"></i>
<div id = \"dropdown_$id\" class = \"dropdown-content\">
[html code here isn't relevant]
</div>
</div>
When I open inspect element, and I click the button, it outputs the function name:
And when I type the function name into the console, the dropdown opens like it should. So why doesn't it do it when I click?
Not sure if it is needed, but here is the script I am using to open/close the dropdown.
function dropDown_$id() {
document.getElementById(\"dropdown_$id\").classList.toggle(\"show\");
}
window.onclick = function(event) {
console.log(event.target);
if (!event.target.matches('#dropdown_$id') && !event.target.matches('#elipses_$id')) {
var dropdown = document.getElementById(\"#dropdowm_$id\");
var c;
if(dropdown != null){
for (c = 0; c < dropdown.length; c++) {
var openDropdowns = dropdown[c];
if (openDropdowns.classList.contains('show')) {
openDropdowns.classList.remove('show');
}
}
}
}
}
EDIT: This is the raw HTML of the dropdown that is spat out after PHP is run:
<div id="dropdown_26" class="dropdown-content">
<div id="names" style="border-bottom: thin solid #BDBDBD;">
<h2 class="dropdown-contenth2">Francois van Kempen</h2>
<p style="color:grey;margin-top:-20px; margin-left: 16px;">#Bork_Bork</p>
</div>
div id="settings" style="border-bottom: thin solid #BDBDBD;">
<a id="a1" class="dropdown-contenta" href="settings.php">Accout Settings</a>
<form id="dark_mode_form" action="nightmode.php" method="POST" style="padding: 10px; display:flex;justify-content:flex-start;align-content:center">
<label style="" class="switch">
<input onchange="this.form.submit()" type="checkbox" name="darkmode" value="checked">
<span class="slider round"></span>
</label>
<p class="dropdown-contentp" style="margin:0;padding:0; margin-left:5px;margin-top:5px;">Night mode</p>
</form>
</div>
<a id="a2" class="dropdown-contenta" href="logout.php">Log out #Bork_Bork</a>
<a id="a3" class="dropdown-contenta" href="reset-password.php">Reset password #Bork_Bork</a>
</div>
EDIT 2: Added the raw script:
<script id="dropdown-settings" type="text/javascript">
function dropDown() {
document.getElementById("dropdown").classList.toggle("show");
}
function dropDown_26() {
document.getElementById("dropdown_26").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
console.log(event.target);
if (!event.target.closest('#dropdown') && !event.target.closest('#navPFP')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
if (!event.target.matches('#dropdown_26') && !event.target.matches('#elipses_26')) {
var dropdown = document.getElementById("#dropdowm_26");
var c;
if(dropdown != null){
for (c = 0; c < dropdown.length; c++) {
var openDropdowns = dropdown[c];
if (openDropdowns.classList.contains('show')) {
openDropdowns.classList.remove('show');
}
}
}
}
}
</script>

Use a javascript function in a generated html code

I'm programming a simple html form with generated code from javascript.
When i run the code in HTML itself it works, but when i put the script in a separate file, it doesn't work anymore. I tried to change the onclick event, generate the code in html, giving my elements a class and add a eventlistner to that, but nothing worked.
this is a part of my javascript code
function print(){
for (var j =0;j<3;j++){
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML="";
for (var i = 0; i<omschList.length;i++){
var li = document.createElement("LI");
if (j==0){
li.innerHTML = (idlist[j+3][i]+"<object align=\"right\" onclick=\"verwijder("+i+")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j+3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
}
function verwijder(index){
for (var i=0;i<3;i++){
idlist[i+3].splice(index, 1);
}
print();
}
EDIT
the full javascript code
(function ($) {
$( document ).ready( function() {
/* VIEWPORT FIXES (http://timkadlec.com/2013/01/windows-phone-8-and-device-width/) */
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement('style');
msViewportStyle.appendChild(
document.createTextNode(
'#-ms-viewport{width:auto!important}'
)
);
document.querySelector('head').appendChild(msViewportStyle);
}
document.getElementById("factuurFormSend").onclick = addLine;
var omschList=[];
var uurprList=[];
var aantalList=[];
var idlist=["omschrijving",
"uurprijs",
"aantal",
omschList,
uurprList,
aantalList]
function addLine(){
omschList.push(document.getElementById("formOmschrijving").value);
uurprList.push(document.getElementById("formUurprijs").value);
aantalList.push(document.getElementById("formUren").value);
print()
}
/*print de lijnen verticaal uit*/
function print(){
for (var j =0;j<3;j++){
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML="";
for (var i = 0; i<omschList.length;i++){
var li = document.createElement("LI");
if (j==0){
li.innerHTML = (idlist[j+3][i]+"<object align=\"right\" onclick=\"verwijder("+i+")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j+3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
/*bereken lijntotaal*/
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].innerHTML=""
var subtotaal=0;
for (var i=0; i<uurprList.length;i++){
var totaal = uurprList[i]*aantalList[i];
subtotaal +=totaal;
var li = document.createElement("LI");
li.innerHTML=totaal;
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].appendChild(li);
}
/*subtotaal en btwtotaal wegschrijven*/
document.getElementById("subtotaal").innerHTML=subtotaal;
document.getElementById("btwbedrag").innerHTML=(subtotaal*0.21);
document.getElementById("totaal").innerHTML=(subtotaal*1.21);
}
function verwijder(index){
for (var i=0;i<3;i++){
idlist[i+3].splice(index, 1);
}
print();
}
} );
})(jQuery);
And the HTML code that worked
<body>
<div class="page">
<header class="header">
</header>
<div role="main" class="cf">
<div class="container" id="factuur">
<section id="header">
<div class="col-sm-8">
<h1>Factuur</h1>
</div>
<div class="col-sm-8">Factuur nr. 1</div>
<div class="col-sm-6">
<div>Naam onderneming<br />
Straatnaam nr<br />
Postcode Gemeente<br />
BE 0123 456 789</div>
</div>
<div class="col-sm-6">
<div>Naam Klant<br />
Straatnaam nr<br />
Postcode Gemeente<br />
BE 0123 456 789</div>
</div>
</section>
<section id="content-header">
<div class="col-sm-6">Omschrijving</div>
<div class="col-sm-2">Uurprijs</div>
<div class="col-sm-2">Aantal</div>
<div class="col-sm-2">Totaal</div>
</section>
<section id="content">
<div class="col-sm-6" id="omschrijving"><ul></ul></div>
<div class="col-sm-2" id="uurprijs"><ul></ul></div>
<div class="col-sm-2" id="aantal"><ul></ul></div>
<div class="col-sm-2" id="lijntotaal"><ul></ul></div>
</section>
<section id="totalen">
<div class="col-sm-offset-7 col-sm-3 text-right">Subtotaal</div>
<div class="col-sm-2" id="subtotaal"></div>
<div class="col-sm-offset-7 col-sm-3 text-right">BTW</div>
<div class="col-sm-2" id="btw">21 %</div>
<div class="col-sm-offset-7 col-sm-3 text-right">BTW Bedrag</div>
<div class="col-sm-2" id="btwbedrag"></div>
<div class="col-sm-offset-7 col-sm-3 text-right" style="border-top:1px solid black;">Totaal</div>
<div class="col-sm-2" id="totaal" style="border-top:1px solid black;"></div>
</section>
<section id="factuurknop">
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#factuurModal">
Voeg een factuurlijn toe
</button>
</section>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="factuurModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Voeg een factuur item toe</h4>
</div>
<form>
<div class="modal-body">
<input style="width:30%" type="text" name="formOmschrijving" id="formOmschrijving" placeholder="Omschrijving">
<input style="width:30%" type="text" name="formUurprijs" id="formUurprijs" placeholder="Uurprijs">
<input style="width:30%" type="text" name="formUren" id="formUren" placeholder="uren">
</div>
<div class="modal-footer">
<button type="button" id="factuurFormSend" class="btn btn-primary">Verzenden</button>
</div>
</form>
</div>
</div>
</div>
<script>
document.getElementById("factuurFormSend").onclick = addLine;
var omschList=[];
var uurprList=[];
var aantalList=[];
var idlist=["omschrijving",
"uurprijs",
"aantal",
omschList,
uurprList,
aantalList]
function addLine(){
omschList.push(document.getElementById("formOmschrijving").value);
uurprList.push(document.getElementById("formUurprijs").value);
aantalList.push(document.getElementById("formUren").value);
print()
}
/*print de lijnen verticaal uit*/
function print(){
for (var j =0;j<3;j++){
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML="";
for (var i = 0; i<omschList.length;i++){
var li = document.createElement("LI");
if (j==0){
li.innerHTML = (idlist[j+3][i]+"<object align=\"right\" onclick=\"verwijder("+i+")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j+3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
/*bereken lijntotaal*/
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].innerHTML=""
var subtotaal=0;
for (var i=0; i<uurprList.length;i++){
var totaal = uurprList[i]*aantalList[i];
subtotaal +=totaal;
var li = document.createElement("LI");
li.innerHTML=totaal;
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].appendChild(li);
}
/*subtotaal en btwtotaal wegschrijven*/
document.getElementById("subtotaal").innerHTML=subtotaal;
document.getElementById("btwbedrag").innerHTML=(subtotaal*0.21);
document.getElementById("totaal").innerHTML=(subtotaal*1.21);
}
function verwijder(index){
for (var i=0;i<3;i++){
idlist[i+3].splice(index, 1);
}
print();
}
} );
</script>
Place your functions in the global scope if you want to assign the click events inline. Not in the load event handler.
Better would be is not to add the click event inline but use event delegation for it. jQuery has great tools for this. Also your code is a weird combination between plain javascript and jQuery functions. It will work, but in my opinion it's better to stay to one style for readability
(function($) {
$(document).ready(function() {
/* VIEWPORT FIXES (http://timkadlec.com/2013/01/windows-phone-8-and-device-width/) */
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement('style');
msViewportStyle.appendChild(
document.createTextNode(
'#-ms-viewport{width:auto!important}'
)
);
document.querySelector('head').appendChild(msViewportStyle);
}
document.getElementById("factuurFormSend").onclick = addLine;
});
function addLine() {
omschList.push(document.getElementById("formOmschrijving").value);
uurprList.push(document.getElementById("formUurprijs").value);
aantalList.push(document.getElementById("formUren").value);
print()
}
})(jQuery);
var omschList = [];
var uurprList = [];
var aantalList = [];
var idlist = ["omschrijving",
"uurprijs",
"aantal",
omschList,
uurprList,
aantalList
]
/*print de lijnen verticaal uit*/
function print() {
for (var j = 0; j < 3; j++) {
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].innerHTML = "";
for (var i = 0; i < omschList.length; i++) {
var li = document.createElement("LI");
if (j == 0) {
li.innerHTML = (idlist[j + 3][i] + "<object align=\"right\" onclick=\"verwijder(" + i + ")\"><u>verwijder</u></object>");
} else {
li.innerHTML = (idlist[j + 3][i]);
}
document.getElementById(idlist[j]).getElementsByTagName("UL")[0].appendChild(li);
}
}
/*bereken lijntotaal*/
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].innerHTML = ""
var subtotaal = 0;
for (var i = 0; i < uurprList.length; i++) {
var totaal = uurprList[i] * aantalList[i];
subtotaal += totaal;
var li = document.createElement("LI");
li.innerHTML = totaal;
document.getElementById("lijntotaal").getElementsByTagName("UL")[0].appendChild(li);
}
/*subtotaal en btwtotaal wegschrijven*/
document.getElementById("subtotaal").innerHTML = subtotaal;
document.getElementById("btwbedrag").innerHTML = (subtotaal * 0.21);
document.getElementById("totaal").innerHTML = (subtotaal * 1.21);
}
function verwijder(index) {
for (var i = 0; i < 3; i++) {
idlist[i + 3].splice(index, 1);
}
print();
}
If you want to be able to delete an object on click you could do this with jQuery and event delegation pretty easily.
//Wait till the initial DOM loading is done
$(document).ready(function() {
//Attach an event handler to the click event to the button the adds a new object
$("#addObject").on('click', function() {
$('#staticParent').append("<div class='deletableObject'>deletable on click</div>")
});
//Attach event delegation from the element with id staticParent to place a function on
//the click event of all elements with the class deletableObject inside the element with
//id staticParent. Because it's event delegation it will work also for elements with this
//class the will be added later dynamicly.
$("#staticParent").on('click', '.deletableObject', function() {
$(this).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="staticParent" style="min-height: 100px">
<div class="deletableObject">deletable on click</div>
</div>
<button id="addObject">Add</button>

Trouble getting event listener to work properly in javascript

So I am a javascript noob. I'm doing an assignment for a webdesign class and we are practicing event listeners. So I had to assign variables to 3 separate divs, place them in an array, create a function to make them display or be hidden, and use a button/click event listener to call the function to call or hide them respectively. this is my code:
var greenBox = document.getElementById("greenBox");
var redBox = document.getElementById("redBox");
var blueBox = document.getElementById("blueBox");
var showALL = document.getElementById("showAll");
var hideALL = document.getElementById("hideAll");
var boxes = [greenBox, redBox, blueBox];
function showBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "block";
}
}
function hideBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "none";
}
}
showALL.addEventListener("click", function() {
showBoxes(boxes);
})
// The "Hide All" button invokes the hideBoxes method
hideALL.addEventListener("click", function() {
hideBoxes(boxes);
})
<form action="#">
<input type="button" id="showAll" value="Show All"><br />
<input type="button" id="hideAll" value="Hide All"><br />
</form>
<div class="box" id="greenBox" style="display:none"></div>
<div class="box" id="redBox" style="display:none"></div>
<div class="box" id="blueBox" style="display:none"></div>
So what the heck am I doing wrong? I've checked multiple times for typos, etc. but everything looks ok to me? It's still not working though.
document.getElementById is case-sensitive.
You have id="showAll" when you are searching for document.getElementById("showALL");.
Pick a consistent case and it should work.
var greenBox = document.getElementById("greenBox");
var redBox = document.getElementById("redBox");
var blueBox = document.getElementById("blueBox");
var showALL = document.getElementById("showAll");
var hideALL = document.getElementById("hideAll");
var boxes = [greenBox, redBox, blueBox];
function showBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "block";
}
}
function hideBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "none";
}
}
showALL.addEventListener("click", function() {
showBoxes(boxes);
})
// The "Hide All" button invokes the hideBoxes method
hideALL.addEventListener("click", function() {
hideBoxes(boxes);
})
.box {width: 200px; height: 36px;}
#redBox {background-color: #F00;}
#greenBox {background-color: #0F0;}
#blueBox {background-color: #00F;}
<form action="#">
<input type="button" id="showAll" value="Show All"><br />
<input type="button" id="hideAll" value="Hide All"><br />
</form>
<div class="box" id="greenBox" style="display:none"></div>
<div class="box" id="redBox" style="display:none"></div>
<div class="box" id="blueBox" style="display:none"></div>
Aside from your initial typo of the div ids document.getElementById("showALL"); should be document.getElementById("showAll");, the divs would also not appear without a size or contents. Something like this should do:
var greenBox = document.getElementById("greenBox");
var redBox = document.getElementById("redBox");
var blueBox = document.getElementById("blueBox");
var showALL = document.getElementById("showAll");
var hideALL = document.getElementById("hideAll");
var boxes = [greenBox, redBox, blueBox];
function showBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "block";
}
}
function hideBoxes(boxes) {
for (i = 0; i < boxes.length; i++) {
boxes[i].style.display = "none";
}
}
showALL.addEventListener("click", function() {
showBoxes(boxes);
});
hideALL.addEventListener("click", function() {
hideBoxes(boxes);
});
<form action="#">
<input type="button" id="showAll" value="Show All"><br />
<input type="button" id="hideAll" value="Hide All"><br />
</form>
<div class="box" id="greenBox" style="display:none;background-color:green;height:20px;width:20px"></div>
<div class="box" id="redBox" style="display:none;background-color:red;height:20px;width:20px"></div>
<div class="box" id="blueBox" style="display:none;background-color:blue;height:20px;width:20px"></div>
The Problem is here in your Selectors
var showALL = document.getElementById("showALL");
var hideALL = document.getElementById("hideALL");
your Element is named "showAll" and you are using "showALL". Notice the capital "L".
As others have said your casing needs to be consistent. One thing that may help you out when debugging this sort of thing is to open up developer tools in your browser(f12 in chrome) and placing breakpoints in the javascript so you can step through and see what the values of your variables are.

What will I add to my code so that when I click the other buttons, the opened element automatically closes?

My code works but I have to double click the button I clicked just to close it. I would like that when I click the other button, the opened element automatically closes.
<div class="col- menu">
<ul>
<li>Picture</li>
<li>About</li>
<li>Size</li>
</ul>
</div>
<div class="content">
<p><span id="pic1"><img src="1.jpg"></span></p>
<p><span id="description" style="display: none;">Cool!</span></p>
<p><span id="size" style="display: none;"><img src="2.jpg"></span></p>
</div>
<script type="text/javascript">
function toggleStuff(id) {
if (document.getElementById(id).style.display == 'block') {
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
</script>
You Can try this:
var stuffArr = ['pic1', 'description', 'size'];
function toggleStuff(id) {
stuffArr.forEach(function(currentId) {
if(currentId === id) {
document.getElementById(id).style.display = 'block';
} else {
document.getElementById(id).style.display = 'none';
}
});
}
You need to loop through all the id''s
Please note this is just demo code to give you an idea
function toggleStuff (id){
//get list of ids
var pic1 = document.getElementById ("pic1");
var size = document.getElementById ("size");
var idSize = 2;
var idArray = Array ("pic1","size");
for (var i = 0; i < idSize; i++){
if (idArray.indexOf (i) == id){
//display id
}else {
//hide id
}
}
}
One out of millions of possible solutions:
function toggleStuff(id) {
var el = document.getElementById(id)
el.classList.toggle('visible');
document.querySelectorAll('.togglable:not(#'+id+')').forEach(function(item) {
item.classList.remove('visible');
})
}
.togglable {
display: none;
}
.visible {
display: block;
}
<div class="col- menu">
<ul>
<li>Picture</li>
<li>About</li>
<li>Size</li>
</ul>
</div>
<div class="content">
<p><span id="pic1" class="togglable">PIC1</span></p>
<p><span id="description" class="togglable">DESCRIPTION</span></p>
<p><span id="size" class="togglable">SIZE</span></p>
</div>

Categories

Resources