I need your help: I have a variable anima, so when myFunction1() is execulted, it will be set to another value. So when I execute myFunction2(), switch case will work accourding to the value that was set on myFunction1(), and than set anima to another value again.
var anima= 1;
function myFunction1(){
switch(anima) {
case 1:
alert("initial value");
break;
case 2:
alert(anima);
break;
case 3:
anime4r();
break;
case 4:
anime5r();
}
var anima= 2;
}
function myFunction2(){
switch(anima) {
case 1:
anime1();
break;
case 2:
alert("it worked");
break;
case 3:
anime4r();
break;
case 4:
anime5r();
}
var anima= 1;
}
Get rid of the var in var anima= 2; and var anima= 1; (in function myFunction2()). You are redefining the variable in a local scope so the change is not to the global variable.
Related
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.
all. I'm fairly new to JavaScript - currently trying to understand the switch statement. I'm having a problem understanding how I still got a return value when I did no assignments to my result variable. The switch statement is nested in a function.
function caseInSwitch(val) {
let result = "";
switch(val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
return result;
}
caseInSwitch(1);
I expect result to be an empty string "", but it shows the following value immediately... without any assignments...!
You're returning in the switch statement. In the case where val equals 1, the switch statement never gets past case 1. The function doesn't return result, it executes return "alpha".
That return statement terminates the function:
function caseInSwitch(val) {
console.log("1: function start. Val:", val);
let result = "";
console.log("2: before switch");
switch(val) {
case 1:
console.log("3: before return alpha");
return "alpha";
console.log("4: after return alpha");
break;
case 2:
return "beta";
break;
case 3:
return "gamma";
break;
case 4:
return "delta";
break;
}
console.log("5: after switch");
return result;
}
var finalResult = caseInSwitch(1);
console.log("Final result:", finalResult);
As you can see, only statements 1-3 get logged.
The return statement in the switch also means the breaks are redundant:
switch(val) {
case 1:
return "alpha";
case 2:
return "beta";
case 3:
return "gamma";
case 4:
return "delta";
}
Those break statements are only necessary to terminate the case, if you're not returning out of the case:
let variable = "";
switch(val) {
case 1:
variable = "alpha";
break;
case 2:
variable = "beta";
break;
case 3:
variable = "gamma";
break;
case 4:
variable = "delta";
break;
}
console.log(variable);
The answer is pretty simple, you are passing 1 as the value for val in caseInSwitch. In the switch block, 1 is matched with case 1 and the function returns alpha. Keep in mind the return in the switch block, makes the control return from the function itself and not just from the switch block
This is my example program in JS. I have to iterate or loop inside the switch statement. So I have used goto, but it doesn't working.
Are there any other options to loop this or is my syntax wrong?
var input = 1;
switch (input)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
if (..) { }
else
{
goto case 2;
}
break;
default:
alert("No Return");
break;
}
Are there any possibilities to use "goto" inside switch statement in javascript?
No, there are no possibilities to use "goto" inside switch statement, or anywhere else, since JavaScript has no such statement.
To solve your problem, as suggested in a comment, organize your cases (moving 3 above 2) so you can use fall-through:
var input = 1;
switch (input)
{
case 1:
...
break;
case 3:
...
if (..) { ...; break; }
// fall through to case 2
case 2:
...
break;
default:
alert("No Return");
break;
}
In this case, make sure to comment the fall-through so people looking at your code don't think it's a bug. You may also need to add a hint so that your linter does not complain.
Or, just put the logic common to 2 and 3 in a little function:
function someLogicFor2Or3() { ... }
case 2:
someLogicFor2OrMaybe3();
break;
case 3:
...
if (..) { }
else someLogicFor2OrMaybe3();
break;
I have used the following technique to do this :
var input = 1;
while (1) {
switch (input) {
case 1:
...
break; // switch
case 2:
...
break; // switch
case 3:
...
if (..) { }
else {
input = 2; // goto case 2;
continue; // while
}
break; // switch
default:
alert ("No Return");
break; // switch
}
break; // while
}
In javascript switch statements, I would like to execute some function if any one of the case is satisified:
switch (myVar){
case 0:
do_something_0();
break;
case 1:
do_something_1();
break;
// I want to execute myFunc() if myVar === 1 or myVar === 2
}
I came up with the idea of having auxiliary variable haveMatched, like this.
var haveMatched=false;
switch (myVar){
case 0:
do_something_0();
haveMatched=true;
break;
case 1:
do_something_1();
haveMatched=true;
break;
}
if (haveMatched){
do_finally();
}
I think there might be better way of achieving this (for example, I would've tried the similar way if I hadn't known about the default: keyword). Am I doing it right, or am I missing something?
If you rewrite your code to include a default case you don't have to include haveMatched = true in every case.
var haveMatched=true;
switch (myVar){
case 0:
do_something_0();
break;
case 1:
do_something_1();
break;
default:
haveMatched = false;
}
if (haveMatched){
do_finally();
}
Why not put the function in the case:
switch (myVar){
case 0:
do_something_0();
do_finally();
break;
case 1:
do_something_1();
do_finally();
break;
}
Include the function in every case block, you don't need a flag...
switch (myVar){
case 0:
do_something_0();
do_finally();
break;
case 1:
do_something_1();
do_finally();
break;
}
this is a workaround:
try {
switch (option) {
case 0:
console.log("option 0");
break;
case 1:
console.log("option 1");
break;
default:
}
} catch (err) {
throw err;
} finally {
doActionFinally();
}
I'm trying to simplify some information on my play-site.
There are two dif. user-types, students and others.
Many places and stores offer a discount to students, and I would therefore make this accessible with a checkbox that changes some of the scripts.
This Is my example (simplifyed as good as i could):
<head>
<script TYPE="text/javascript" SRC="script/script_uteplasser.js"></script>
</head>
<body>
<form action="">
<input type="checkbox" id="checkbox_student" onclick="student();"><span>I'm A student!</span></input></form>
(...)
</body>
javascript (script_uteplasser):
//--------------------SAMFUNDET---------------------
samfundet = "...blablablabla..." + cc_samfundet() + "...blablablabla...";
//----INNGANGSAV. SAMFUNDET----
var checkbox1 = document.getElementById("checkbox_student");
function student(){
if (checkbox1.checked){
function cc_samfundet(){var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 1: return "Free"; break; case 2: return "Free"; break; case 3: return "Free"; break; case 4: return "Free"; break; case 5: return "Free"; break; case 6: return "Free"; break; case 0: return "Free";}}
}
else{
function cc_samfundet(){var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 1: return "100,-"; break; case 2: return "100,-"; break; case 3: return "100,-"; break; case 4: return "100,-"; break; case 5: return "100,-"; break; case 6: return "100,-"; break; case 0: return "100,-";}}
}
}
//-------------------------------------------------
This doesn't kill the script, but isn't returning any information either.
Why do you want to redefine function ?
You can check in your function if checkbox is checked. If you want really to redefine function use this code :
//declare your function :
function cc_samfundet () {
//...
}
//or :
var cc_samfundet2 = function () { /* ... */ };
//redefine your function :
cc_samfundet = function () {
//...
}
//or with an existing function :
cc_samfundet = cc_samfundet2;
It doesn't return anything because you're only defining your function(s) in your evaluation. If you add a second pair of parentheses afterwards, it should work how you intend.
That said, this is a really poor design pattern. First of you don't really need to make what you're doing functions here. Second is creating the same named function twice with completely separate logic - that pretty much brakes every good programming principle.
Update: Here is something to point you in the right direction,
var checkbox1 = document.getElementById("checkbox_student");
// Assuming this function should do something else too?
function student() {
cc_samfundet(checkbox1.checked);
}
var cc_samfundet = function (isStudent) {
var d = new Date();
var theDay = d.getDay();
switch (theDay) {
case 1:
return isStudent ? "Free" : "100,-";
// and so on
}
}