From IF/ELSE to Switch in Javascript - javascript

So, I'm trying to substitute the code within the IF statements to run the same way in a Switch statement. However, I can't seem to understand how to get the functions to run the same way in the switch as they do in the if statement. Here's the code I've written with the if statement. Could anyone help me figure out how to format it correctly to run with the switch statement instead?
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
if (i == 5) {
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}
i++;
}

I am not sure why you want the switch but for sample purposes here is how a switch would work for the code you posted above:
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
switch(i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
break;
default:
// any code you want to run in the else statement
}
i++;
}

This switch statement would replace the current if statement that you have.
switch (i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}

Related

Changing style through JavaScript doesn't work with variables

I want to do is change the left margin of a DOM element based on a variable in JavaScript. This function works:
function updateTabs(i) {
console.log('Switching to tab ' + i)
switch(i) {
case 0:
document.querySelector('#About-content1').style.marginLeft = "0";
break;
case 1:
document.querySelector('#About-content1').style.marginLeft = "-100%";
break;
case 2:
document.querySelector('#About-content1').style.marginLeft = "-199%";
break;
default:
break;
}
}
This successfully sets the margin-left property like I want it to. However, I don't want to call document.querySelector every time I call the updateTabs function. I tried this:
var contentDiv1 = document.querySelector('#About-content1');
function updateTabs(i) {
console.log('Switching to tab ' + i)
switch(i) {
case 0:
contentDiv1.style.marginLeft = "0";
break;
case 1:
contentDiv1.style.marginLeft = "-100%";
break;
case 2:
contentDiv1.style.marginLeft = "-199%";
break;
default:
break;
}
}
However, this only works the first time I call the function. After that, it prints "Switching to tab" but doesn't actually modify the style. Is there any way I could change the style without having to call document.querySelector every time?
I think the reason is that the second time around it doesn't know what contentDiv1 is how about you put that inside the function like this:
function updateTabs(i) {
var contentDiv1 = document.querySelector('#About-content1');
console.log('Switching to tab ' + i)
switch(i) {
case 0:
contentDiv1.style.marginLeft = "0";
break;
case 1:
contentDiv1.style.marginLeft = "-100%";
break;
case 2:
contentDiv1.style.marginLeft = "-199%";
break;
default:
break;
}
}
So now everytime the function runs it knows what contentDiv1 is. So now you still call document.querySelector only once but the function know what you want.
The question is missing some context, but if Hadi Pawar's answer isn't correct, my guess is that the element is being destroyed and recreated. This should validate that:
var contentDiv1 = document.querySelector('#About-content1');
contentDiv1.myResize = function(i) {
console.log('Switching to tab ' + i)
var offsets = [0, -100, -199];
if( i > offsets.length ) return;
this.style.marginLeft = offsets[i] + '%';
}
[...]
contentDiv1.myResize( n );
Now, when you call resize, you will get a hard error if 'contentDiv1' loses scope. Otherwise, the logic is contained within the element itself.
Turns out that the problem was that I had a Vue.js element connected to the same element, so the element was changed. I moved the Vue.js declaration to before the const contentDiv1 = document.querySelector('#About-content1'), and it fixed the problem.

Click event: switch statement not working

I´m trying to trigger multiple click events depending on the var clicked, however the switch statement isn´t working. I think it´s the "var" inside the Switch parameter but I have no idea how to correct it:
var buttonQ = document.getElementById('Heater1button');
var buttonW = document.getElementById('Heater2button');
var buttonE = document.getElementById('Heater3button');
var buttonA = document.getElementById('Heater4button');
var buttonS = document.getElementById('Heater6button');
var buttonD = document.getElementById('OpenHHbutton');
var buttonZ = document.getElementById('KicknHat');
var buttonX = document.getElementById("Kickbutton");
var buttonC = document.getElementById('CClosedHHbutton');
$(document).click(function() {
switch (var) {
case buttonQ:
document.getElementById('Q').play(), $("#displaytext").text("Heater 1")
break;
case buttonW:
document.getElementById('W').play(), $("#displaytext").text("Heater 2")
break;
case buttonE:
document.getElementById('E').play(), $("#displaytext").text("Heater 3")
break;
case buttonA:
document.getElementById('A').play(), $("#displaytext").text("Heater 4")
break;
case buttonS:
document.getElementById('S').play(), $("#displaytext").text("Heater 6")
break;
case buttonD:
document.getElementById('D').play(), $("#displaytext").text("Open HH")
break;
case buttonZ:
document.getElementById('Z').play(), $("#displaytext").text("KicknHat")
break;
case buttonX:
document.getElementById('X').play(), $("#displaytext").text("Kick")
break;
case buttonC:
document.getElementById('C').play(), $("#displaytext").text("Closed HH")
break;
}
})
You shouldn't use a switch statement, use event listeners attached to each element.
buttonQ.addEventListener("click", function() {
document.getElementById('Q').play(), $("#displaytext").text("Heater 1");
});
buttonW.addEventListener("click", function() {
document.getElementById('W').play(), $("#displaytext").text("Heater 2");
});
and so on for all the buttons.
Something like this?
$(document).click(function(e) {
var id = e.target.id;
switch (id) {
case "Heater1button":
document.getElementById('Q').play(), $("#displaytext").text("Heater 1")
break;
case "Heater2button":
document.getElementById('W').play(), $("#displaytext").text("Heater 2")
break;
}
});
You're correct, the issue is the var inside the switch statement. What variable does this refer to? A switch statement is used to "check the result of a and do one of x, y, etc". In your example I don't see any declaration of a value called "var" that the switch is using to evaluate what case to run.
In any event, even if you did have a variable somewhere else in your code called var, it won't work because that is a reserved word. You can't name a variable using the word you use to name variables.
You are switching on var, which itself does not appear to exist from the code you have provided. You need to know what was clicked, so you need to use what the jQuery .click() method provides - "this". Or perhaps in your case you should switch on $(this).attr("id").
See this: https://api.jquery.com/click/

Shortband for switch..case doesn't work

I am clueless why this piece of code doesn't work:
switch (Category.getValue()) {
case 1: () => { for (var i = 0; i < 12; i++) OptionSet.addOption(options[i]); }; break;
default: () => { OptionSet.clearOptions(); }; break;
}
It hits case 1:, but then instead of doing loop it just quits switch statement.
With your code () => {} You are essentially defining an anonymous function without assigning or calling it. You can remove that part from the code and it will work. Example

Switch Statement and jQuery hasClass function

I am trying to use a switch statement to check if the current page has a specific body class. This is kind of what I am looking for:
var bodyClass = $('body').hasClass('className')
switch(bodyClass) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
I do understand that the jQuery hasClass function returns true of false and is used like $('body').hasClass('someClassName') and this will return true or false. Also, my body typically has about 7-10 different class names for a given page.
This is not the use case for a switch in my opinion, but a simple set of branches
var body = $('body');
if(body.hasClass('abc')) {
}
else if(body.hasClass('def')) {
}
else {
/* default case */
}
/* etc */
I agree with the other answer that you're better suited to just use if, else if statements here, but an alternative would be to rip the classes off the body tag and check them against your strings:
var bodyClasses = ($('body').attr('class') || '').split(' ');
for (var i = 0, len = bodyClasses.length; i < len; i++) {
switch(bodyClasses[i]) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
}
I know this is an old thread, but it may help someone else.
If you are able to ensure the classes for the element are declared in a specific order, you could ensure the class you are checking for is first / last in the list, and use something similar to this:
var bodyClass = $('body').attr('class');
var firstClass = bodyClass.slice(0, bodyClass.indexOf(' '));
switch(firstClass) {
case 'homepage':
// Some code here
break;
case 'residential-page':
// Other code here
break;
default:
// More code here
}

Beginner JavaScript: change if, else if, else to switch

Im in an intro JavaScript class and I have a homework assignment where I need to switch a picture every 5 seconds. I had it written out as a if, else if, else statement and it worked fine but then I saw on the directions that it's supposed to be a switch statement. Now I am having a tough time getting it to work. If anyone can help me out and let me know what Im doing wrong, that'd help a lot.
This is what I had:
var currAd = "pic1";
function changeAd() {
if (currAd == "pic2") {
document.images[0].src = "cvb1.gif";
currAd = "pic1";
}
else if (currAd == "pic3") {
document.images[0].src = "cvb2.gif";
currAd = "pic2";
}
else {
document.images[0].src = "cvb3.gif";
currAd = "pic3";
}
}
This is the switch statement. I assume its not working because of the currAd variable being the same on all of the cases, but I dont know what to switch it to
var currAd;
function changeAd() {
switch (currAd) {
case currAd:
return document.images[0].src = "cvb2.gif";
case currAd:
return document.images[0].src = "cvb3.gif";
default:
return document.images[0].src = "cvb1.gif";
}
}
Each case is the value you're comparing currAd with. You're currently comparing it to itself, when you should be comparing it to pic2, pic3, etc.
switch(curaAd) {
case "pic1":
// ...
Change your switch statement to:
switch (currAd) {
case "pic1":
return document.images[0].src = "cvb2.gif";
case "pic2":
return document.images[0].src = "cvb3.gif";
default:
return document.images[0].src = "cvb1.gif";
}

Categories

Resources