How do I run the same javascript with incrementing variable names - javascript

I have the following code, I know it's super inefficient, though I don't know how to make it simpler. Is there a way that button1 could just be changed to buttonX and everything could just be written once?
Apologies if this has been asked before. I have tried searching but it is quite a complicated thing to describe and I haven't found anything relevant.
var button1 = document.getElementById('toggle1');
var button2 = document.getElementById('toggle2');
var button3 = document.getElementById('toggle3');
var button4 = document.getElementById('toggle4');
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var div4 = document.getElementById('div4');
button1.onclick = function() {
div1.style.display = 'block';
div2.style.display = 'none';
div3.style.display = 'none';
div4.style.display = 'none';
};
button2.onclick = function() {
div1.style.display = 'none';
div2.style.display = 'block';
div3.style.display = 'none';
div4.style.display = 'none';
};
button3.onclick = function() {
div1.style.display = 'none';
div2.style.display = 'none';
div3.style.display = 'block';
div4.style.display = 'none';
};
button4.onclick = function() {
div1.style.display = 'none';
div2.style.display = 'none';
div3.style.display = 'none';
div4.style.display = 'block';
};

Have a try with this - I have taken your code as example since you did not post HTML
The advantage of these two examples is that when you need to add a button and a div, the code does not change at all.
const buttons = document.querySelectorAll("[id^toggle]");
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
const divs = document.querySelectorAll("[id^=div]");
for (let i = 0; i < divs.length; i++) {
divs[i].style.display = divs[i].id == "div" + this.id.replace("toggle", "") ? "block" : "none";
}
}
}
Instead of ID selector and replace, you can use classes and data-attr
const buttons = document.querySelectorAll(".toggleButton");
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
const divs = document.querySelectorAll(".toggleDiv");
const showId = this.getAttribute("data-toggle");
for (let i = 0; i < divs.length; i++) {
divs[i].style.display = divs[i].id == showId ? "block" : "none";
}
}
}
assuming <button data-toggle="div1" class="toggleButton" type="button">Div1</button>

Consider placing everything into an array so you can do things by index.
var buttons = [];
var divs = [];
for(let i = 0; i < 4; i++) {
buttons[i] = document.getElementById('toggle'+(i+1));
divs[i] = document.getElementById('div'+(i+1));
buttons[i].addEventListener('click', doClick(i));
}
function doClick(index) {
return function() {
for(let i = 0; i < 4; i++) {
divs[i].style.display = i === index ? 'block' : 'none';
}
};
}
doClick(0)();
<div id="div1">One</div>
<div id="div2">Two</div>
<div id="div3">Three</div>
<div id="div4">Four</div>
<button id="toggle1">1</button>
<button id="toggle2">2</button>
<button id="toggle3">3</button>
<button id="toggle4">4</button>
In this code I am getting all four buttons and divs in a loop and setting up the event listeners for each button.
The function doClick is a curried function that uses a closure to set the index of the button that is being clicked on so we know which one we want to show and then we hide all of the others.

With jQuery you could do the following:
$('.toggleButton').on('click', function() {
var toggleDivId = '#toggleDiv' + $(this).attr('id').replace('toggleButton', '');
$('.toggleDiv').css('display', 'none');
$(toggleDivId).css('display', 'block');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggleButton1" class="toggleButton">Button 1</button>
<button id="toggleButton2" class="toggleButton">Button 2</button>
<button id="toggleButton3" class="toggleButton">Button 3</button>
<button id="toggleButton4" class="toggleButton">Button 4</button>
<div id="toggleDiv1" class="toggleDiv">Div 1</div>
<div id="toggleDiv2" class="toggleDiv">Div 2</div>
<div id="toggleDiv3" class="toggleDiv">Div 3</div>
<div id="toggleDiv4" class="toggleDiv">Div 4</div>

You can use javascript objects of course!
// let's match keys (1, 2, 3, 4) to buttons
var buttons = {
1: document.getElementById('toggle1'),
2: document.getElementById('toggle2'),
3: document.getElementById('toggle3'),
4: document.getElementById('toggle4')
}
// let's match keys (1, 2, 3, 4) to divs
var divs = {
1: document.getElementById('div1'),
2: document.getElementById('div2'),
3: document.getElementById('div3'),
4: document.getElementById('div4')
}
// this function will hide all divs except the once given as a param
function hideAllBut(index) {
// go through each div
for (var i = 1; i <= 4; i++) {
// if i is equal to the param, display the div
if (i === index) {
divs[i].style.display = 'block'; // accessing the divs object which has key i
} else {
// else hide it
divs[i].style.display = 'none';
}
}
}
// now for each button, we call the function to hide all expect the one we want
buttons[1].onclick = function () {
hideAllBut(1);
};
buttons[2].onclick = function () {
hideAllBut(2);
};
buttons[3].onclick = function () {
hideAllBut(3);
};
buttons[4].onclick = function () {
hideAllBut(4);
};
Keeping that in mind, we can make the code even more dynamic
var buttons = {};
var divs = {};
// how many elements we have (here 4)
var totalElements = 4;
// assign buttons and divs values dynamically, while adding the onclick
for (var i = 1; i <= totalElements; i++) {
buttons[i] = document.getElementById('toggle' + i); // i.e. if i=1, 'toggle'+i = 'toggle1'
divs[i] = document.getElementById('div' + i);
buttons[i].onclick = function () {
hideAllBut(i);
};
}
// this function does the same as how we wrote it perviously but with a different format
function hideAllBut(index) {
for (var i = 1; i <= totalElements; i++) {
// we use the ternary operator
divs[i].style.display = (i === index) ? 'block' : 'none';
}
}
Read the documentation of the javascript object because you're gonna use it a lot and will help you do stuff dynamically. https://www.w3schools.com/js/js_objects.asp
Ternary operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Here's an example using jQuery, that helps to avoid having to declare all the vars for each button first.
I also added a 'reset' button so you can get all the divs back. I'm not sure if this is what you wanted but to me this seems like the kind of thing jQuery is especially helpful for, so here is an example:
$('button').on('click', function(){
$('.boxdiv').css({"display":"none"});
switch ($(this).attr('id')) {
case "1":
case "2":
case "3":
case "4":
$(`#div${$(this).attr('id')}`).css({"display":"block"});
break;
case "reset":
$('.boxdiv').css({"display":"block"});
break;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="float:left">
<button class="button" id="1">B1</button>
<button class="button" id="2">B2</button>
<button class="button" id="3">B3</button>
<button class="button" id="4">B4</button>
<button class="button" id="reset">Reset</button>
</div>
<br/>
<br/>
<div class="boxdiv" id="div1" style="background-color:red;width:60px;height:60px;float:left;">
</div>
<div class="boxdiv" id="div2"style="background-color:yellow;width:60px;height:60px;float:left;">
</div>
<div class="boxdiv" id="div3"style="background-color:blue;width:60px;height:60px;float:left;">
</div>
<div class="boxdiv" id="div4"style="background-color:green;width:60px;height:60px;float:left;">
</div>

Related

Can't get the correct number of buttons with specific class name

I want to count the number of buttons inside a div, I add the buttons dynamically from a js file. When I run the program on the browser, the buttons appear correctly and when I inspect the code from the browser all the elements and class names are correct. However, when I try to log the number of buttons with a class name of "accordion" it returns 0 when it should return 4.
Here's the HTML code:
<body class="d-flex justify-content-center" style="width: 100%;height: 50%;">
<div class="container" style="width: 500px;"><img src="assets/img/header_image.png" style="width: 100%;">
<div class="row" style="margin-top: 20px;">
<div id="accordion-div" class="col">
</div>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="index.js"></script>
The javascript code:
var acc = document.getElementsByClassName("accordion");
var acc_div = document.getElementById("accordion-div")
var i;
add_accordion_item = (name, details) => {
var btn = document.createElement('button');
acc_div.appendChild(btn);
btn.innerHTML = name;
btn.className += "btn btn-success accordion";
btn.type = "button"
var details = document.createElement('div');
acc_div.appendChild(details);
details.innerHTML = details
details.className += "panel"
}
url = '.....'
make_list = () => {
$.getJSON(url, function(data){
for(var i = 0; i<data["number_of_threats"]; i++){
name = data["info"][i]["name"];
details = "details"
add_accordion_item(name, details);
}
});
}
make_list()
console.log(document.getElementsByClassName("accordion").length)
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
This should show a button that when pressed it should show the div with the details. But the for never runs as the acc.length is 0.
Thanks for you time
I think that a node array don't get length attribut.
You should use forEach instead of for loop like
acc.forEach(function(element) {
element.addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
})
I hope it helps you
I think you have missed to add a class accordion as to any element. because I cant see any element with a class name as accordion in your html code.
But inside to your javascriptcode, on first line you are trying to search an element with a class name as accordion.
The variable acc doesn't auto update after you declared it in the beginning.
You will need to retrieve the value of acc variable again just above the for loop.
i.e. just above the for loop you need to add the line like this
acc = document.getElementsByClassName("accordion");
for (i = 0; i < acc.length; i++) {
....
I fixed it by adding the listener inside the make_list function
var acc = document.getElementsByClassName("accordion");
var acc_div = document.getElementById("accordion-div")
var i;
add_accordion_item = (name, details) => {
var btn = document.createElement('button');
acc_div.appendChild(btn);
btn.innerHTML = name;
btn.className += "btn btn-success accordion";
btn.type = "button"
var details = document.createElement('div');
acc_div.appendChild(details);
details.innerHTML = details;
details.className += "panel";
add_listener(btn);
}
url = '.....'
make_list = () => {
$.getJSON(url, function(data){
for(var i = 0; i<data["number_of_threats"]; i++){
name = data["info"][i]["name"];
details = "details"
add_accordion_item(name, details);
}
});
}
make_list()
function add_listener(element) {
element.addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}

More efficient way of writing this as part of a JavaScript function?

I am trying to write a JavaScript function that will hide multiple IDs at once. As I will be getting into 50 or so IDs that will need to be hidden for any given function, I don't want to have unnecessary code. I have something like below, but there must be a way to combine all these lines in to one, no?
document.getElementById("aMap").style.display = "none";
document.getElementById("aList").style.display = "none";
document.getElementById("bMap").style.display = "none";
document.getElementById("bList").style.display = "none";
document.getElementById("cMap").style.display = "none";
document.getElementById("cList").style.display = "none";
Ok, thanks everyone. Showing my updated code below. It's not working, as I am sure I am doing something wrong. The goal is to have a function that shows 2 elements that are identified by ID and hide all of the other IDs at the same time:
function zShowHideRest() {
var zOther = ["aMap", "aList", "bMap", "bList", "cMap", "cList"];
zOther.forEach.getElementById().style.display = "none";
document.getElementById("zMap").style.display = "block";
document.getElementById("zList").style.display = "block";
}
Am I in the ballpark or is what I did way off?
Just put all of the IDs in an array and iterate over them using a for of or forEach loop.
const arr = [your list of ids];
for(const a of arr) {
document.getElementById(a).style.display = "none";
}
const arr = [your list of ids];
arr.forEach((a) => {
document.getElementById(a).style.display = "none";
})
Using a loop helps reduce repeated code:
const ids = ["aMap","aList","bMap","bList","cMap","cList"];
ids.forEach(
function(id) {
const element = document.getElementById(id);
if (element) {
element.style.display = "none";
}
}
);
document.getElementById("aMap").style.display = "none";
document.getElementById("aList").style.display = "none";
document.getElementById("bMap").style.display = "none";
document.getElementById("bList").style.display = "none";
document.getElementById("cMap").style.display = "none";
document.getElementById("cList").style.display = "none";
// method of array of id REF Sebastian Simon
let arrID = ["aMap", "aList", "bMap", "bList", "cMap", "cList",]
// method 1 for loop
for (var i = 0; i < arrID.length; i++) {
document.getElementById(arrID[i]).style.display = "none";
};
// method 2 for loop
arrID.forEach((id) => {
document.getElementById(id).style.display = "none";
});
// arrow function not working any of IE
// my suggest
// give your elements same class example:"hide"
document.getElementsByClassName("hide").style.display = "none";
quickFix: you either use for loop but using class name makes without array of id but i have array of elements which is has classname hide
let elementsHasHide = document.getElementsByClassName("hide");
for (var i = 0; i < elementsHasHide.length; i++) {
elementsHasHide[i].style.display="hide"
}
You should use Class instead of ID.
var myClasses = document.querySelectorAll('.ids_list'),
i = 0,
l = myClasses.length;
for (i; i < l; i++) {
myClasses[i].style.display = 'none';
}
or
var list = document.getElementsByClassName('my-class')
for (var i = 0; i< list.length; i++){
list[i].style.display = "none";
}
html:
<div class="ids_list" id="aMap"></div>
<div class="ids_list" id="aList"></div>
<div class="ids_list" id="bMap"></div>
<div class="ids_list" id="bList"></div>
<div class="ids_list" id="cMap"></div>
<div class="ids_list" id="cList"></div>
Just update js

Can a javascript function apply to all elements of a certain CSS class?

I have a nav bar where each button changes the background of the body. They each change it to a different color. I have created onmouseover and onmouseout functions for each button to achieve this. However, I wonder if there is a way to just write one of each function by just referring to them by their class? They all have the same class of button. Is there a way a function can apply to all elements of a certain class? My code:
function whichButton(x) {
if (x==1)
return "red";
if (x==2)
return "green";
if (x==3)
return "blue";
if (x==4)
return "orange";
if (x==0)
return initBG;
}
button1.onmouseover = function() {
document.body.style.backgroundColor = whichButton(1);
}
button1.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button2.onmouseover = function() {
document.body.style.backgroundColor = whichButton(2);
}
button2.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button3.onmouseover = function() {
document.body.style.backgroundColor = whichButton(3);
}
button3.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button4.onmouseover = function() {
document.body.style.backgroundColor = whichButton(4);
}
button4.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
initBG just saves the initial background of the page.
I have tried this:
document.getElementsByClassName('button').onmouseover = function() {
document.body.style.backgroundColor = whichButton(1);
}
but it doesn't trigger the function. And I guess to do this, I'd also need to have a way to read the elements' ID as a string so I could get it's number...
This is more out of curiosity than necessity, just trying to find ways to keep my code small! I could see this being useful in many applications so I'd love to learn more about this!
Corresponding HTML:
<div id="navbar">
<p id="button1" class="button">Red</p><p id="button2" class="button">Blue</p><p id="button3" class="button">Green</p><p id="button4" class="button">Orange</p>
</div>
Here is my suggestion to solve it:
Use the data attribute and iterate over all elements with the given class.
function applyColor(element) {
var color = element.getAttribute('data-bg');
document.body.style.backgroundColor = color;
}
var buttons = document.getElementsByClassName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("mouseover", function() {
applyColor(this);
}, false);
}
<nav>
<button class="button" data-bg="red">red</button>
<button class="button" data-bg="blue">blue</button>
<button class="button" data-bg="yellow">yellow</button>
<button class="button" data-bg="green">green</button>
<button class="button" data-bg="pink">pink</button>
<button class="button" data-bg="magenta">magenta</button>
</nav>
As previously stated, getElementsByClassName returns a collection and you can't just add the event to the collection in a way that you can in jQuery. To do this is pure JS, you need to use a for loop and then attach the event to each individual element as below:
var buttons = document.getElementsByClassName('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onmouseover = function (event) {
var colour = event.target.className.split(" ")[1];
document.body.style.backgroundColor = colour;
}
}
http://jsfiddle.net/andyfurniss/1n5vann9/
getElementsByClassName returns a collection. So you will have to loop over it and you shall be good.
var buttons = document.getElementsByClassName('button');
[].forEach.call(buttons, function (button){
var id = parseInt(button.id.split("").reverse().join("")); //This will give you the number from the id
button.onmouseover = = function() {
document.body.style.backgroundColor = whichButton(id);
}
button.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
});
To ensure ES6 compatibility, there is much better way.
var buttons = document.getElementsByClassName("button");
for (button of buttons) {
var id = parseInt(button.id.split("").reverse().join("")); //This will give you the number from the id
button.onmouseover = = function() {
document.body.style.backgroundColor = whichButton(id);
}
button.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
}
The first comment actually solved it for me. I did this:
document.onmouseover = function() {
var x = event.target;
y = x.id.toString().replace('button','');
if (y > 0 && y <= 4)
document.body.style.backgroundColor = whichButton(y);
}
document.onmouseout = function() {
var x = event.target;
y = x.id.toString().replace('button','');
if (y > 0 && y <= 4)
document.body.style.backgroundColor = whichButton(0);
}
If I mouse over a "button", it removes the word "button", leaving the number (1-4), then sends that to my whichButton function to decice which colour to use. Nice and simple, works for me.
You can use event delegation, which means attaching an event listener to an ancestor, then inspecting the event.target to decide what to do.
Demo: http://jsfiddle.net/a58tj1ak/
// given your HTML and whichButton function like this:
function whichButton(x) {
var initBG = '#fff';
if (x==1)
return "red";
if (x==2)
return "green";
if (x==3)
return "blue";
if (x==4)
return "orange";
if (x==0)
return initBG;
}
// get the buttons into an array
var buttons = [].slice.call(document.getElementsByClassName('button'));
// add event listener to the #navbar element
document.getElementById('navbar').addEventListener('mouseover', function(e){
// target is an element being hovered
var target = e.target;
// check if the target is in the array of buttons
var index = buttons.indexOf( e.target );
if( index > -1 ){
document.body.style.backgroundColor = whichButton(index + 1)
}
else {
document.body.style.backgroundColor = whichButton(0);
}
});

Display and hide column in HTML by using Javascript

I am writing up an webpage to display a table with 2 columns and two rows(header and body).
I would like to control the show and hide of any of this 2 columns with Javacript.
The hide and display should be determined by the value of "input1" and"input2" from server.
If "input1"="empty"(string), hide colomn1(col1). Otherwise, display it.
Similar logic applying to "input2" and "col2"
I printed the value "input1" in the webpage and confirmed it is equal to "empty". However, the "col1" is still in the table displayed.
Can anyone point out the problem? If my approach is incorrect, please advise what is the best alternative.
<table>
<tr>
<th class="col1">Genus</th>
<th class="col2">Species</th>
</tr>
<tr>
<td class="col1">column1</td>
<td class="col2">column2</td>
</tr>
</table>
<script type="text/javascript">
function check()
{
if({{input1}}=="empty")
document.getElementByID("col1").style.display = "none";
else
document.getElementByID("col1").style.display = "block";
if({{input2}}=="empty")
document.getElementByID("col2").style.display = "none";
else
document.getElementByID("col2").style.display = "block";
}
</script>
I can see two big mistakes over there:
The method "getElementById" will not work since you're not selecting an element by its id, you're selecting it by its class. How to do that? I'll suggest you to download the jQuery library ( http://jquery.com/ ) and then search how to select elements by its class name. jQuery is, in some way, a javascript wrapper that will make your life much easier :)
Setting the "display" property to "none" should hide it, but setting if to "block" will probably screw the table up. You should either set it to "table-cell" or "table-header-group" depending on if it's td or th. I suggest you look at the documentation of the display property: http://www.w3schools.com/cssref/pr_class_display.asp
I hope it helped :)
EDIT: if you don't want to use jquery, check at this post: How to Get Element By Class in JavaScript?
Yes, it can be done. Here's a quick example: http://jsfiddle.net/vZB5k/
<body>
<table>
<tr>
<th class="col1">Genus</th>
<th class="col2">Species</th>
</tr>
<tr>
<td class="col1">
column1
</td>
<td class="col2">
column2
</td>
</tr>
</table>
<input type="button" id="hideCol1" value="Hide Column 1" />
<input type="button" id="hideCol2" value="Hide Column 2" />
<input type="button" id="hideBoth" value="Hide Both" />
<input type="button" id="showAll" value="ShowAll" />
<script>
var hideCol1 = function () {
var e = document.getElementsByClassName("col1");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
var hideCol2 = function () {
var e = document.getElementsByClassName("col2");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
var hideBoth = function () {
hideCol1();
hideCol2();
};
var showAll = function () {
var e = document.getElementsByClassName("col1");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "table-cell";
};
e = document.getElementsByClassName("col2");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "table-cell";
};
};
(function () {
document.getElementById("hideCol1").addEventListener("click", hideCol1);
document.getElementById("hideCol2").addEventListener("click", hideCol2);
document.getElementById("hideBoth").addEventListener("click", hideBoth);
document.getElementById("showAll").addEventListener("click", showAll);
})();
</script>
</body>
Updated - using "input" variables:
var hideCol1 = function () {
var e = document.getElementsByClassName("col1");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
var hideCol2 = function () {
var e = document.getElementsByClassName("col2");
for (var i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
};
(function () {
if (input1 !== "on") {
hideCol1();
}
if (input2 !== "on") {
hideCol2();
}
})();
This should do the trick
<script>
function hideCol() {
if (document.getElementById("txt1").value != "") {
var elements = document.getElementsByClassName('col1')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
if (document.getElementById("txt2").value != "") {
var elements = document.getElementsByClassName('col2')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
}
</script>
check out this fiddle
update the code as per your requirement .. but it has code to select the elements to be hidden.
Edit 1
Here is the new fiddle
have made to work according to checkboxes
function hidecol() {
if (document.getElementById("txt1").checked) {
var elements = document.getElementsByClassName('col1')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
if (document.getElementById("txt2").checked) {
var elements = document.getElementsByClassName('col2')
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
}
}
please let me know if this was helpful

Menu Toggle function not working properly

This works fine at all times except for the first time tab_toggle(0) is called.
when the first time this function is called the #box_home has display:block; so the function shouldn't do anything but whats happening is #box_port(the next div) is getting display:block; and #box_home remaining display:block as before. why is this happening. is it because when the function is called the variable has value undefined so doing some random thing.
Please answer this in javascript only, dont answer in jquery.
i couldnt make it work just this part in jsfiddle so i am sharing the entire webpage code
http://goo.gl/dhTUDH
<!-- Javascript -->
<script>
function tab_toggle(x) {
console.log("tab_toggle");
var home = document.getElementById("box_home").style;
var port = document.getElementById("box_port").style;
var about = document.getElementById("box_about").style;
var contact = document.getElementById("box_contact").style;
var box = [home,port,about,contact];
switch (x) {
case 0:
if (home.display == "block") {
console.log('end');
} else if (port.display == "block") {
box[0].display = "block";
box[1].display = "none";
} else if (about.display == "block") {
box[1].display = "block";
box[2].display = "none";
} else {
box[2].display = "block";
box[3].display = "none";
}
break;
default:
if (home.display == "block") {
box[0].display = "none";
box[1].display = "block";
} else if (port.display == "block") {
box[1].display = "none";
box[2].display = "block";
} else if (about.display == "block") {
box[2].display = "none";
box[3].display = "block";
} else {}
break;
}
}
<!-- HTML -->
◀
▶
<div id="box_home"></div>
<div id="box_port"></div>
<div id="box_about"></div>
<div id="box_contact"></div>
<!-- CSS -->
#box_home{display:block;}\
#box_port{display:none;}
#box_about{display:none;}
#box_contact{display:none;}
You can't access a style directly as a property, as in
home.display
Instead, use the getComputedStyle() method
getComputedStyle(home).display
element.style will get the element's inline style. Try getComputedStyle or add a class.
getComputedStyle(box[0]).getPropertyValue("display")
Not sure what would you achieve, but this should work:
var currentElement = 0;
(tab_toggle = function (x) {
var home = document.getElementById("box_home").style;
var port = document.getElementById("box_port").style;
var about = document.getElementById("box_about").style;
var contact = document.getElementById("box_contact").style;
var box = [home, port, about, contact];
if (currentElement + x < 0 || currentElement + x > box.length - 1)
return;
currentElement += x;
console.log("toggled " + currentElement);
for (var i = 0; i < box.length; i++) {
box[i].display = "none";
}
box[currentElement].display = "block";
})(0);

Categories