unwanted situations after creating button in javascript - javascript

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?"

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/

From IF/ELSE to Switch in 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";
}

switch between functions with checkboxes?

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
}
}

Trying to make an on/off/auto button

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);
}

Categories

Resources