Trying to make an on/off/auto button - javascript

I am new to javascript and am trying to make a button that cycles through on/off/auto each click. Each state also has to run code in the if statement and code in the switch as well. I currently cannot seam to get it to run right. Later Once I get this working I want the "if statement" function to be in its own .js file so I can reference it for other on/off/auto buttons. While the switch will be apart of the main code. What am I doing wrong?
function cycle()
{
var onoffB = ();
if (document.getElementById("button1").value="On")
{
onoffB=1;
document.getElementById("button1").value="Off";
}
else if (document.getElementById("button1").value="Off")
{
onoffB=2;
document.getElementById("button1").value="Auto"
}
else
{
onoffB=0;
document.getElementById("button1").value="On"
}
switch(onoffB)
{
case 0:
//running code;
break;
case 1:
//running code;
break;
case 2:
//running code;
break;
}
}
</script>
</head>
<body>
<input type="button" id="button1" value="On" onclick="cycle()">
</body>
</html>

Well, there are two big problems I see right off the bat. First of all, the following syntax is invalid JavaScript:
var onoffB = ();
I think what you mean there is to have an undefined state for onoffB, which your'e better off doing with:
var onoffB = null;
Secondly, you're using assignment (=) instead of comparison (== or ===). (As a rule of thumb, you should always prefer === over == unless you have a very good reason and know what you're doing.) Consider the following:
var x = 3; // *sets* the value of x to 3
var x == 3; // invalid syntax
var x === 3; // invalid syntax
if( x = 2 ) { print 'x is 2'; } // will *always* print 'x is 2', no matter what
// the value of x is; x now has the value 2
// PROBABLY NOT WHAT YOU WANT
if( x = 0 ) { print 'x is 0'; } // will *never* print 'x is 0', no matter what
// the value of x is; x now has the value 0
// PROBABLY NOT WHAT YOU WANT
if( x === 5 ) { print 'x is 5'; } // will only print 'x is 5' if the value of x
// is 5; value of x
if( x === 0 ) { print 'x is 0'; } // will only print 'x is 0' if the value of x
// is 0; value of x unchanged
There are a lot of stylistic things I would change about this too. Your code's really difficult to read because of your formatting choices. Furthermore, there's a lot of unnecessarily repeated code. If I were writing this, I would shorten it to the following:
switch( document.getElementById("button1").value ) {
case 'On':
// do stuff
break;
case 'Off':
// do stuff
break;
case 'Auto':
// do stuff
break;
default:
// probably an error condition; show message, maybe?
break;
}
If you really need the value of the on/off/auto button, you can set it inside the case bodies.

On this line:
var onoffB = ();
You need to either remove the initializer or replace the parentheses with something else.
In each of your if statements:
if (document.getElementById("button1").value="On")
You're setting the value, making it always true. You probably want to compare using == rather than assigning with = here.
While it's not really a problem but rather a possible improvement, I'd recommend putting the result of document.getElementById in a variable so you don't have to keep calling it. It should be rather quick on its own, but doing it once will probably be faster.

Here's the complete working and running code:
<html>
<head>
<script type="text/javascript">
function cycle()
{
var onoffB = null;
if (document.getElementById("button1").value == "On")
{
onoffB = 1;
document.getElementById("button1").value = "Off";
}
else if (document.getElementById("button1").value == "Off")
{
onoffB = 2;
document.getElementById("button1").value = "Auto";
}
else if (document.getElementById("button1").value == "Auto")
{
onoffB = 0;
document.getElementById("button1").value = "On";
}
switch(onoffB)
{
case 0:
//running code;
break;
case 1:
//running code;
break;
case 2:
//running code;
break;
}
}
</script>
</head>
<body>
<input type="button" id="button1" value="On" onclick="cycle();">
</body>
</html>
As you can see, the main problems were:
You set var onoffB = (); while it should have been null.
You should have used the "==" instead of "=".
Another 'else if' was missing for when the value is 'Auto'.
I hope I've helped :-)

Try something like this:
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
var state = 'On';
function onOffAuto(element){
var e = element;
switch(state){
case 'On':
e.value = state = 'Off';
return;
case 'Off':
e.value = state = 'Auto';
return;
case 'Auto':
e.value = state = 'On';
return;
}
}
E('button1').onclick = function(){
onOffAuto(this);
}

Related

How to use setInterval() to call a click function periodically within another function?

this is my first programming in Java. I have two functions, #start and #reset. I want to use setInterval to use #reset function within #start after every 10 seconds.
Here are the two functions. First is #start
$('#start').click(function() {
// Calculate the amount of time in milliseconds to run for
var timeleft_s = Math.round(
parseInt($('#hours' ).val())*3600 +
parseInt($('#minutes').val())*60 +
parseInt($('#seconds').val())*1
);
if (timeleft_s > 2147483647) { // Max unsighed 32 bit value
alert("That's too long. Pick a shorter time.");
return;
}
if (APP.last_sent_status !== null && APP.last_sent_status !== APP.status) {
return false;
}
// 0 : not started
// 1 : running
// 2 : stopped
switch(APP.status) {
case 0:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
case 1:
APP.stopMCA(APP.channel);
APP.last_sent_status = 2;
break
case 2:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
default:
break
}
APP.updateButtonStates();
});
Here is the reset function
$('#reset').click(function() {
APP.resetHistogram(APP.channel);
});
I want to use setInterval inside the start function make sure the reset function executes after every 10 seconds.
Here is what I have tried so far with no luck. Any help is appreciated:
$('#start').click(function() {
// Calculate the amount of time in milliseconds to run for
var timeleft_s = Math.round(
parseInt($('#hours' ).val())*3600 +
parseInt($('#minutes').val())*60 +
parseInt($('#seconds').val())*1
);
if (timeleft_s > 2147483647) { // Max unsighed 32 bit value
alert("That's too long. Pick a shorter time.");
return;
}
if (APP.last_sent_status !== null && APP.last_sent_status !== APP.status) {
return false;
}
// 0 : not started
// 1 : running
// 2 : stopped
switch(APP.status) {
case 0:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
case 1:
APP.stopMCA(APP.channel);
APP.last_sent_status = 2;
break
case 2:
APP.resumeMCA(APP.channel, timeleft_s);
APP.last_sent_status = 1;
break
default:
break
}
setInterval(#reset,10000)
APP.updateButtonStates();
});
function resetFunction(){
APP.resetHistogram(APP.channel);
}
$('#reset').click(resetFunction);
then replace
setInterval(#reset,10000) with
setInterval(resetFunction,10000)
since you defined the function to be called on #reset click as anonymous there's no reference as such by which you can call it.
so you define it by giving it a name, and then use that in place of onclick function as well as inside your start function
I am not totally sure of this answer. If you are trying to start a setInterval inside of the onclick of #start, here's what I think you could do:
setInterval(() => $("#reset").onclick(),10000);

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.

Why won't a simple Javascript if condition execute?

<!DOCTYPE html>
<html>
<body>
<button onClick="Display()"></button>
<script>
function Display() {
var a = 0;
if(a = 0){
alert("hello world");
}
}
</script>
</body>
</html>
I run the page and clicked the button and nothing happens. I can't for the life of me figure out why...
Edit: on another note, THIS code executes no matter what, even if I haven't defined var CorrectActivities:
function Display() {
if(CorrectActivities = 3) {
document.getElementById("ActivitiesResult").innerHTML = '<span>style="color:DarkGreen;font-weight:bold;font-size:30px;">3 out of 3 correct!</span>';
} else if (CorrectActivities = 2) {
document.getElementById("ActivitiesResult").innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">2 out of 3 correct!</span>';
} else if (CorrectActivities = 1) {
document.getElementById("ActivitiesResult").innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">1 out of 3 correct!</span>';
} else {
document.getElementById("ActivitiesResult").innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">0 out of 3 correct!</span>';
}
}
Edit2: thanks for the answers. First code is fixed, second is still broken regardless of what I try. Going to look for errors elsewhere in the script...
When you compare values, you should use == (equal) or === (equal and same type). = is only for setting variable value.
<!DOCTYPE html>
<html>
<body>
<button onClick="Display()"></button>
<script>
function Display() {
var a = 0;
if(a == 0){
alert("hello world");
}
}
</script>
</body>
</html>
To your another code, I created a jsfiddle. There you have same problem as in first part, wrong comparison operator. It didn't run if CorrectActivities wasn't declared. I fixed it (like in first part), declared variable and added three buttons to test all cases and it seems to work.
You also have small typo in case 3, you have an extra closing bracket at <span>style
a = 0 is assignment not a valid condition. a == 0, a === 0 or !a will all work for what you want.
Same is the case with CorrectActivities, use CorrectActivities == 3 instead of CorrectActivities = 3.
in javascript = assign a value and return it, == or === compare values
The first part wont execute because:
You click the button
Display get called
if(a = 0) evaluate to if(0) which is to javascript if(false)
so the code inside if won't run. what you want is if(a == 0):
function Display() {
var a = 0;
if (a == 0) {
alert("hello world");
}
}
<button onClick="Display()"></button>
for the second part if(CorrectActivities = 3) will be if(3) which is to javascript if(true) so it will always run. again what you want is using the == operator:
function Display () {
if ((CorrectActivities == 3)) {
document.getElementById('ActivitiesResult').innerHTML = '<span>style="color:DarkGreen;font-weight:bold;font-size:30px;">3 out of 3 correct!</span>'
} else if ((CorrectActivities == 2)) {
document.getElementById('ActivitiesResult').innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">2 out of 3 correct!</span>'
} else if ((CorrectActivities == 1)) {
document.getElementById('ActivitiesResult').innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">1 out of 3 correct!</span>'
} else {
document.getElementById('ActivitiesResult').innerHTML = '<span style="color:Crimson;font-weight:bold;font-size:30px;">0 out of 3 correct!</span>'
}
}
This is because instead of comparing,you are assigning it.
So the statement if(a = 0) always comes out to be true.
Use == instead of =.
function Display() {
var a = 0;
if(a = 0){
alert("hello world");
}
}
This will help.

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
}

Having trouble with continue/breaks in javascript

So I'm currently a novice programmer writing in javascript, and I'm having trouble understand why my continue/break statements aren't working in my code. I appreciate any help, thanks!
document.getElementById("start").onclick = function(){
for (var i = 0; i < myArray.length; i++){
var x = Math.random();
x = 6*x;
x = Math.floor(x);
document.getElementById("question").innerHTML = myArray[x];
document.getElementById("start").innerHTML = "Enter";
document.getElementById("start").onclick=function(){
if (document.getElementById("text").value==aArray[x]){
document.getElementById("question").innerHTML = "You are correct!";
countPoints++;
document.getElementById("count").innerHTML = countPoints;
document.getElementById("start").innerHTML = "Next";
document.getElementById("start").onclick = function(){
continue;
}
} else {
document.getElementById("question").innerHTML = "Wrong! Gameover!";
break;
}
}
}
}
Your break/continue are inside child functions. break/continue only apply to loops at the SAME code level, but since you're executing them inside sub-functions where there are no loops, there's nothing to break/continue, and they're effectively "do nothing" statements.
in more detail:
document.getElementBy("start").onclick = function() {.... break; ...}
only DEFINES a function which contains a break. The function will not execute until the start element is clicked on, at which time your for loop isn't even running anymore.
It's like putting a "meet me for lunch on dec 10th" note inside a christmas present, and then wondering why no one showed up on the 10th - well, they didn't get the note until the 25th.

Categories

Resources