Javascript: Changing variable on button click - javascript

I have a javascript file linked to index.html like below:
<script src='game.js' type='text/javascript'>
</script>
Assume that game.js contains:
var speed = ...;
Along with some other content.
I have 3 buttons on the HTML page that when clicked I want to change the variable speed in the javascript. Once clicked I want all 3 buttons to be disabled or hidden until the reset button is clicked. Any idea how I go about this?

Using pure HTML/JavaScript, here's what I would do:
<form name="form1">
<span id="buttons">
<input type="button" name="button1" value="Speed1"/>
<input type="button" name="button2" value="Speed2"/>
<input type="button" name="button3" value="Speed3"/>
</span>
<input name="reset" type="reset"/>
</form>
<script type="text/javascript">
var speed, buttonsDiv=document.getElementById("buttons");
for (var i=1; i<=3; i++) {
var button = document.form1["button" + i];
button.onclick = function() {
speed = this.value;
alert("OK: speed=" + speed);
buttonsDiv.style.display = 'none';
};
}
document.form1.reset.onclick = function() {
speed = null;
alert("Speed reset!");
buttonsDiv.style.display = 'inline';
return true;
};
</script>
Here is a working example: http://jsfiddle.net/maerics/TnTuD/

Create functions within your javascript files that attach to the click events of each button.
The functions would change the variable you want.
aButtonelement.addEventListener('click',functionToChangeVariable,false)

Include the following in your Javascript file:
function DisableButtons() {
speed = 100;
document.getElementById("btn_1").disabled = true;
document.getElementById("btn_2").disabled = true;
document.getElementById("btn_3").disabled = true;
}
function EnableButtons() {
document.getElementById("btn_1").disabled = false;
document.getElementById("btn_2").disabled = false;
document.getElementById("btn_3").disabled = false;
}
In your HTML, assign the following onClick events:
<button onClick="DisableButtons();">Button 1</button>
<button onClick="DisableButtons();">Button 2</button>
<button onClick="DisableButtons();">Button 3</button>
<button onClick="EnableButtons();">Reset</button>

something like this? http://jsfiddle.net/qMRmn/
Basically, speed is a global variable, and clicking a button with the class set-speed class will set the speed to a new value, and disable all of the set-speed buttons. Clicking the reset button will re-enable them.
The code should be fairly self explanatory.

Easiest way, use jQuery.
$("#idofbutton").click(function () {
// change variables here
});
Or you could register an event:
document.getElementById("idofbutton").addEventListener('click', function () {
// change variables here
}, false);
Source

Related

simple task javascript buttons in html

Can someone please help me make a button which prints thank you when clicked? I know there are lots of ways to do this but in my circumstance, I need to use an if statement and this has me totally stumped. I have not done much because I am totally unsure of what syntax to use. I have made a website for a school project and it has a form on one of the pages. It is a requirement to use javascript to do something with an if statement. I would like to have a button at the bottom of the form which does something to the page when clicked. I don't really mind what happens but I thought a thank you message would be nice.
Cheers :)
<!DOCTYPE html>
<html>
<body>
<button id="sub">Subscribe</button>
</body>
<script>
function button () {
var message = document.getElementById("message");
if (sub.onclicked == true) {
/*Pop up with thank you*/
};
};
button ();
</script>
</html>
If you need if then you can test if button was clicked only once. But first thing is that you need an event that will fire when button is clicked, and document.getElementById value need to match you html id attribute.
function button () {
var message = document.getElementById("sub");
var cliked = false
message.onclick = function() {
if (!cliked) {
cliked = true;
alert('Thank you');
}
};
}
button();
<button id="sub">Subscribe</button>
The key issue here is you're trying to introduce code that has no use. For example here's how you add a message to the page when you click a button:
const button = document.querySelector('#sub');
const message = document.querySelector("#message");
button.addEventListener('click', handleClick, false);
function handleClick(event) {
message.textContent = 'Hallo';
};
<button id="sub">Subscribe</button>
<div id="message" />
There's no room for an if statement here given the basic code example you have in your question. Your assignment may even be marked down if you start adding unnecessary code. That's why I suggested having a look at your requirements and changing them.
For example you might decide you want two buttons that give different messages when you click on them, using an if statement to differentiate between them:
// Because we have two buttons we use a class instead of an id
// and we can pick them up with `querySelectorAll`
const buttons = document.querySelectorAll('.sub');
const message = document.querySelector("#message");
// Instead of attaching one event listener to one element we
// loop over our buttons and attach an event listener to each one
buttons.forEach(button => button.addEventListener('click', handleClick, false));
function handleClick(event) {
// We destructure the dataset id from the button that was clicked
const { target: { dataset: { id } } } = event;
// And we use an if statement to choose between two different messages
if (id === 'msg1') message.textContent = 'Hallo';
if (id === 'msg2') message.textContent = 'Secret message!';
};
<!-- Each button has its own data attribute -->
<button data-id="msg1" class="sub">Button 1</button>
<button data-id="msg2" class="sub">Button 2</button>
<div id="message" />
Further reading:
querySelector and querySelectorAll
Destructuring assignment
Data attributes
addEventListener
<button id="sub">Subscribe</button>
<script>
document.getElementById("sub").addEventListener("click", () =>{
document.write("thank you");
});
</script>
or, if you don't want it to remove all your elements:
<button id="sub">Subscribe</button>
<p id="text"></p>
<script>
document.getElementById("sub").addEventListener("click", () =>{
document.getElementById("text").innerHTML = "thank you!";
});
</script>
<!DOCTYPE html>
<html>
<body>
<button id="sub" onclick="button(event)">Subscribe</button>
<script>
function button(event) {
var message = document.getElementById("message");
if (event) {
/*Pop up with thank you*/
alert("Thank you");
}
};
</script>
</body>
</html>

Switch Div value with class attribute

I want to switch value from div to input and submit.
This's my codes so far
HTML
<form id="forms" action="content.php" method="post">
<input id="foo" type="hidden" value"">
</form>
<div class="btn" value="1" width="40" height="40"></div>
<div class="btn" value="2" width="40" height="40"></div>
Javascript
function $(v) {
return document.getElementById(v);
}
var btn = document.getElementsByClassName('btn');
for(i=0; i<btn.length; i++) {
btn[i].addEventListener('click', function() {
btn.getAttribute('value') = $('foo').value;
$('forms').submit();
}, false);
}
Why it dont work? can't be clicked? thx
I think you are doing the assignment wrong. You need to assign the value of the div button to your hidden foo field. Also, btn is the array of all buttons, you can use this inside event handler callback to reference the button that was clicked since this context is bound to the element that has the attached event. I think the following is what you want:
(function() {
function $(v) {
return document.getElementById(v);
}
var btn = document.getElementsByClassName('btn');
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener('click', function() {
// assign what was clicked (this) to the foo hidden value
$('foo').value = this.getAttribute('value');
// now submit
$('forms').submit();
}, false);
}
}());
Edit: Example using Array's forEach instead (which I assume would be available in your execution environment since you are using getElementsByClassName method.
(function() {
function $(v) {
return document.getElementById(v);
}
var buttons = document.getElementsByClassName('btn');
// each element of the array is passed to the provided callback
buttons.forEach(function (button) {
button.addEventListener('click', function() {
// assign what was clicked (this) to the foo hidden value
$('foo').value = this.getAttribute('value');
// now submit
$('forms').submit();
}, false);
});
}());
im not sure what the purpose of this is,
but if you insist on using divs as radio buttons or w.e
use data attributes,
like so
<div id="div1" data-value="1"></div>
and you can use jquery to get the attribute like this:
var div1 = $('#div1').data('value')
or
var div1 = $('#div1').attr('data-value');
on click listeners also with jquery
$('#div1').on('click', function(){
// do your thing here
...
})
Firstly, I don't think divs should have a value attribute. Maybe you should switch it to data-value, which can be used easily in jQuery:
<form id="forms" action="content.php" method="post">
<input id="foo" type="hidden" value"">
</form>
<div class="btn" data-value="1" width="40" height="40"></div>
<div class="btn" data-value="2" width="40" height="40"></div>
As for the javascript:
$('.btn').on('click', function() {
$(this).data('value', $('#foo').val());
$('#forms').submit();
});

Disable load function untill button is selected in javascript?

Hi this is an odd question and i will try to ask it correctly. I have a function using javascript called load canvas.
function loadCanvas(canvas) {
relevant code here...
}
I also have a normal button called btn.
<button class="btn" type="button">Play!</button>
I am wondering can i disable the function until the play button is selected? The function is for a game using javascript. So on load there isnt anything there until i press play then it appears!
any ideas/help please?
$(document).ready(function(){
var loadCanvas= function (canvas) {
relevant code here...
}
$("#test").on('click',loadCanvas()); // using jquery
document.getElementById("test").addEventListener("click",loadCanvas()); // using javascript
<button class="btn" id="test" type="button">Play!</button>
})
If you are having issue because other method is triggering the function you can add a flag with a boolean and turn it on when you click..
Something like that:
The button don't change at all
<button class="btn" type="button">Play!</button>
The js code with this change:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
And in the on click function add this before call the function:
buttonClicked = true;
At the end your js should look like this:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
$(".btn").click(function(){
buttonClicked = true;
var canvas = ...;
loadCanvas(canvas );
});
EDIT
If you have more buttons with the class .btn you should use an id and change the selector of the .click() with the selector of the id instead of the class selector
As you mentioned in the comments <script type="text/javascript"> loadCanvas("game"); </script> You are calling the function as soon as the page loads. So you will have to change it to:
<button class="btn play-button" type="button">Play!</button>
<script type="text/javascript">
$('.play-button').click(function(e){
loadCanvas("game");}
);
</script>
If you are not using jquery you will have to handle the click event by javascript.
You got to do following:
function loadCanvas(game) {
alert('loading canvas');
}
<button class="btn" type="button" onclick="loadCanvas('game')">Play!</button>

Day/Night mode - CSS + JQuery - Cookies?

I'm testing javascript code for day/light background switch and I don't know how to do something. I'm newbie to javascript, so I'm learning new stuff.
So what I want to do?
When I click for example on button "Day" (which change background to yellow), I want that style for yellow background stay in the code after page is refreshed. I heard something about Cookies/LocalStorage, but I don't know how to implement it for this code.
Feel free to change whole code if you know easier way to do this, but please explain why it's better or why it should be like that.
Thanks in advance for your help.
Here is the code:
HTML:
<body id="body">
<input type="button" onclick="day();" value="Day" />
<input type="button" onclick="night();" value="Night" />
<input type="button" onclick="reset();" value="Reset" />
</body>
CSS:
.darkSwitch {
background: #808080;
}
.lightSwitch {
background: #ffff99;
}
JavaScript:
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function() {
var button = $('input[type=button]');
button.on('click', function() {
button.not(this).removeAttr('disabled');
$(this).attr('disabled', '');
});
});
Last edit: now disabling selected button on page load, CODE NOT IN THIS POST, see the latest JSFiddle
Explanation
What I did:
The code is put in between<script> tags at the end of the <body> (personnal preference)
I added the parameter event to the onClick event of the button element.
I added event.preventDefault() at the start of the onclick event of the button element: ensuring the page is NOT refreshed on the click of a button.
Warning: ALL the buttons will behave the same in your page. If you have other buttons, I suggest you add another class for those three buttons and bind the event on the button.myClass element.
I added a condition on the button state change, so the reset button won't get disabled.
eval($(this).val().toLowerCase()+"();"); gets the value of the the clicked button and executes the function attached to it.
Solution
HTML
<body id="body">
<input type="button" class="changeBg" onclick="day();" value="Day" />
<input type="button" class="changeBg" onclick="night();" value="Night" />
<input type="button" class="changeBg" onclick="reset();" value="Reset" />
</body>
JavaScript
(JSFiddle) <-- Check this out Updated with classes & cookies
function day() {
body.className = "lightSwitch";
};
function night() {
body.className = "darkSwitch";
};
function reset() {
body.className = "";
};
$(function () {
/* RegEx to grab the "bgColor" cookie */
var bgColor = document.cookie.replace(/(?:(?:^|.*;\s*)bgColor\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var button = $('input[type=button].changeBg');
button.on('click', function (event) {
event.preventDefault();
/* Executing the function associated with the button */
eval($(this).val().toLowerCase() + "();");
button.not($(this)).removeAttr('disabled');
if ($(this).val() != "Reset") {
$(this).attr('disabled', '');
/* Here we create the cookie and set its value, does not happen if it's Reset which is fired. */
document.cookie = "bgColor="+$(this).val();
}
});
/* If the cookie is not empty on page load, execute the function of the same name */
if(bgColor.length > 0)
{
eval(bgColor.toLowerCase()+'()');
/* Disable the button associated with the function name */
$('button[value="'+bgColor+'"]').attr("disabled","disabled");
}
});
I recommend you don't use cookies unless localStorage is not supported. They slow your site down.
if(localStorage){
localStorage.setItem("bgColor", "lightSwitch");
}else{
document.cookie = "bgColor=lightSwitch";
}

Javascript click function not working

I'm trying to write a simple javascript function that will clone some html input fields when the user clicks a button, but for some reason the button's click function isn't being called when I click it. Any ideas why?
Here's the javascript:
<SCRIPT LANGUAGE="JavaScript">
$(document).ready(
function(){
$("#default-label").hide();
$("#default-element").hide();
var counter = parseInt($("#counter").val());
$("#addProduct").click(
function(){
var product = $('#fieldset-default');
var newProduct = product.clone(true);
newProduct.insertAfter(product);
document.getElementById("addProduct").innerHTML = 'Add More';
$("#counter").val(++counter);
}
);
}
);
</script>
My HTML for the button:
<button id="addProduct" type="button" name="add">Add Product</button>
i think you missed jquery plugin,included latest version of jquery library, if not there.

Categories

Resources