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.
Related
I want the variable CurrectcoinValue will get the value of the correct case, but it's not working.
const CurrectcoinValue = "null";
const symbol = "usdt";
casim(symbol, CurrectcoinValue);
console.log("result : " + CurrectcoinValue);
function casim(symbol, CurrectcoinValue) {
switch (symbol) {
case "btc":
CurrectcoinValue = "BTC";
break;
case "eth":
CurrectcoinValue = "ETH";
break;
case "usdt":
CurrectcoinValue = "USDT";
break;
case "usdc":
CurrectcoinValue = "USDC";
break;
default:
CurrectcoinValue = 1;
}
}
There are 2 fundamental problems with your solution:
If you want to be able to change a variable, you need to declare it with let or var (preferably let because the scope is tighter). const is used when explicitly you don't want a variable to be changed.
You can't set a string variable from within a function, JS won't change that variable since it doesn't keep a reference to it!
Also, i think that we have a better way to treat this, which is using a function that does not change any parameter reference, only calculating the value:
const symbol = "usdt";
const CurrectcoinValue = casim(symbol);
console.log("result : " + result);
function casim(symbol) {
switch (symbol) {
case "btc":
return "BTC";
case "eth":
return "ETH";
case "usdt":
return "USDT";
case "usdc":
return "USDC";
default:
return 1;
}
}
This way you are not battling with reference issues.
You could also take the advice of using the symbol.toUpperCase(); method for the cases that are not the default, that would save some code repetition :)
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/
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";
}
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
}
}
I need to create a button dynamically with javascript. so i wrote these codes in between "script" tags.
window.onload = function () {
var newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = 'What's the day today?';
newButton.id = 'btn1';
newButton.onclick = myfunction();
div1.appendChild(newButton);
}
function myfunction() {
var x = new Date().getDay();
switch (x) {
case 0: alert("sunday"); break;
case 1: alert("monday"); break;
case 2: alert("tuesday"); break;
case 3: alert("wednesday"); break;
case 4: alert("thursday"); break;
case 5: alert("friday"); break;
case 6: alert("saturday"); break;
}
}
when the page is loaded, "myfunction()" function is running automatically. after that when i press this button, nothing happens. what's my mistake?
You need to change
newButton.onclick = myfunction;
When you do newButton.onclick = myfunction(); it executes the myfunction and then assigns the value returned by it to the onclick handler, in this case undefined. What you need to do is to pass the function reference to the onclick property
Also I assume the following is a copy paste change
newButton.value = 'What's the day today?'; // you need to escape ' with \' or use "What's the day today?"