I am trying to make a simple toggle button in javascript - javascript

I am trying to make a simple toggle button in javascript. However, the button will only turn "OFF" and will not turn back "ON"
<html><head></head>
<script type="text/javascript">
function toggle(button)
{
if(document.getElementById("1").value=="OFF"){
document.getElementById("1").value="ON";}
if(document.getElementById("1").value=="ON"){
document.getElementById("1").value="OFF";}
}
</script>
<body>
<form action="">
<input type="button" id="1" value="ON" style="color:blue"
onclick="toggle(this);">
</form></body></html>
I am running:HP Netbook : Ubuntu Linux 10.04 : Firefox for Ubuntu 1.0.

Why are you passing the button if you're going to look it up?
Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON.
// Toggles the passed button from OFF to ON and vice-versa.
function toggle(button) {
if (button.value == "OFF") {
button.value = "ON";
} else {
button.value = "OFF";
}
}
If you wanna get fancy and save a couple of bytes you can use the ternary operator:
function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";}

Both of your if statements are getting executed one after each other, as you change the value and then immediately read it again and change it back:
function toggle(button)
{
if(document.getElementById("1").value=="OFF"){
document.getElementById("1").value="ON";}
else if(document.getElementById("1").value=="ON"){
document.getElementById("1").value="OFF";}
}
Adding the else in there should stop this happening.

Another method to do this is:
var button = document.querySelector("button");
var body = document.querySelector("body");
var isOrange = true;
button.addEventListener("click", function() {
if(isOrange) {
body.style.background = "orange";
}else {
body.style.background = "none";
}
isOrange = !isOrange;
});
In the JavaScript file.
/*****
NOTE!
Another way is applying a class to the element that we want to change.
The CSS file must have the class with the format we want:
.orange {
background: orange;
}
By last in our js file we only need to make the application of the class:
var button = document.querySelector("button");
button.addEventListener("click", function() {
document.body.classList.toggle("orange");
});
Regards :)

Why not use a switch?
function toggle(button)
{
switch(button.value)
{
case "ON":
button.value = "OFF";
break;
case "OFF":
button.value = "ON";
break;
}
}

<html>
<head>
<script type="text/javascript">
function toggle(button)
{
if(document.getElementById("1").value=="OFF")
{
document.getElementById("1").value="ON";
}
else
{
document.getElementById("1").value="OFF";
}
}
</script>
</head>
<body>
<form action="">
<input type="button" id="1" value="ON" style="color:blue" onclick="toggle(this);">
</form>
</body>
</html>

This will resolve your issue.
let isOn = true;
function toggle(button) {
isOn = !isOn;
if (isOn) {
document.getElementById("1").value = "ON";
} else {
document.getElementById("1").value = "OFF";
}
}

Related

button tag alway disabled in index.html

I am working on a Phonegap Build app for Android. I created two buttons with onclick which triggers a doHelper function that will disable the buttons after. But for some reason the buttons are always disabled even before clicking on the buttons.
Here is my code.
html:
<div class="gameHelper">
<div class="row">
<div class="twelve columns">
<button onclick="doHelper('skip')" class="skipAnswer button helperButtons">
Skip
</button>
<button onclick="doHelper('remove')" class="removeOneAnswer button helperButtons">
Remove 1
</button>
</div>
</div>
js:
function doHelper(helperName) {
if (helperName == 'skip') {
var classVar = '.skipAnswer';
skipAnswerUsed = true;
$(classVar).attr('disabled', 'disabled');
$(classVar).css('background-color', 'red');
submitAnswer(activeNumber);
} else if (helperName == 'remove') {
var classVar = '.removeOneAnswer';
removeOneAnswerUsed = true;
$(classVar).attr('disabled', 'disabled');
$(classVar).css('background-color', 'red');
}
}
css:
.helperButtons {
width: 49%;
background-color: green;
color: white;
}
I'd recommend seperating the HTML from your JS.
This can be done with event handlers. Since you are already using jQuery, here is one possible way to do that:
$('button.skipAnswer').on('click', function () {
doHelper("skip");
});
$('button.removeOneAnswer').on('click', function () {
doHelper("remove");
});
https://jsfiddle.net/9jczt3uu/
Are you using firefox? Probably that is the problem, I had the same issue some time ago...
You can fix it by adding
$(document).ready(function(){
$(".button").removeAttr('disabled');
});
Your HTML and Javascript is correct. There is probably another issue.
try to this way
function doHelper(helperName) {
$('button').removeAttr('disabled')
$('button').css('background-color', '');
if (helperName == 'skip') {
var classVar = '.skipAnswer';
skipAnswerUsed = true;
$(classVar).attr('disabled', '');
$(classVar).attr('disabled', 'disabled');
$(classVar).css('background-color', 'red');
submitAnswer(activeNumber);
} else if (helperName == 'remove') {
var classVar = '.removeOneAnswer';
$(classVar).attr('disabled', '');
removeOneAnswerUsed = true;
$(classVar).attr('disabled', 'disabled');
$(classVar).css('background-color', 'red');
}
}

Change a div class when a radio option inside it is clicked

This is my first real dive into javascript. I've been going at this for hours and haven't found a solution (though I learned a lot).
<script type="text/javascript">
function changeClass(){
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function()
{
document.getElementById("switcher").addEventListener( 'click' , changeClass );
}
</script>
Here is the HTML:
<div class="switch switch-blue" id="switcher">
<input type="radio" class="switch-input" name="resp" value="1" id="respyes" checked>
<label for="respyes" class="switch-label">YES</label>
<input type="radio" class="switch-input" name="resp" value="2" id="respno">
<label for="respno" class="switch-label">NO</label>
</div>
The default is a blue background. If they choose no I want it red, then back to blue if they click yes, all that is in the css. If I manually change the class from switch-blue to switch-red, it works. Right now it does absolutely nothing.
Thank you!
Problem here is event propagation when an internal element click event bubbleup so it causing calling your function twice which change class and then revert back so try:
function changeClass(event) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
if (window.event != undefined) window.event.cancelBubble = true;
event.stopPropagation();
}
window.onload = function () {
document.getElementById("switcher").addEventListener('click', changeClass);
}
event.stopPropagation(); will stop this bubbling and for IE use window.event.cancelBubble = true;
Here is working JSFiddle
Edit
But this will not guarentee the change of class on radio button click as event is bind to parent div so clicking over div anywhere will trigger the event, so try to bind event on the radio-buttons:
Event on Radio click
function changeClass(clickedItem) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (clickedItem == 1) {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function () {
var yes = document.getElementById('respyes');
var no = document.getElementById('respno');
yes.onclick = function () {
changeClass(2)
};
no.onclick = function () {
changeClass(1)
};
}
function changeClass(elem){
var currentClass = elem.className, blueClass = "switch switch-blue",
redClass= "switch switch-red"
elem.className = (currentClass == blueClass) ? redClass:blueClass;
}
window.onload = function()
{
document.getElementById("switcher").onclick = function(){
changeClass(this);
};
}
JS Fiddle: http://jsfiddle.net/dYt8v/
Looks like it is working fine, when you add the css classes.
Here is a demo. I think you are missing the styles.
Add the style to your head and see if that works for you.
<style>
.switch-blue{
background:blue;
color:#fff;
}
.switch-red{
background:red;
color:#fff;
}</style>
Feel free to change the styles as you need them.
Edit
I just noticed that you have the event listeners attached to the div instead of the radio button. That will change the background when you click the div, instead of the buttons. See this updated fiddle.

Javascript onclick event not firing on first click

The code below is a link which when clicked will open and close an initially hidden div. It works fine other than having to click the link twice in the first instance to open it. It's not a major problem but if it can be made so that the div opens on the first click that would be great.
toggleDiv.js
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function() {
if (!link) return true;
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return true;
});
});
index.html
<body>
<a id="myMagicLink" href="http://www.google.com/">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
<script language="JavaScript" type="text/javascript" src="toggleDiv.js"></script>
</body>
I had the same problem for toggling the display value of an ASIDE tag. Switching from "none" to "inline" and back again would not work on the first click. Display was set to "none" in my CSS file.
In my script I changed "none" to "" (which seems to mean "default" as far as I understand). The following code works fine for me now.
var x = document.getElementsByTagName("aside")[0];
if (x.style.display == "")
{
x.style.display = "inline";
}
else
{
x.style.display = "";
}
I understood this when I saw the CSS/actual values in Firefox developer tools: "aside" is shown with CSS attributes, but an "element" is first shown with no attribute. On first click, "element" was assigned a "display" attribute set to "none".
Not sure what the trouble you are having this... this works flawlessly for me in Chrome.
I did change the url of your link to reflect back to the same document, but the div foo is hiding and reappearing as it should.
Couple of style notes: Rather than setting display = "block" it is better to say display = "" so it can return to its default value.
In addition, I also included a preventDefault function. Your use of return true would work for DOM0 style event handling, but it did not work with the attachEvent/addEventHandler code. This properly keeps the link from being followed.
<html>
<head>
<title>Test</title>
<script>
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function(e) {
if (!link) return cancelDefaultAction(e);
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return cancelDefaultAction(e);
});
});
function cancelDefaultAction(e) {
var evt = e ? e:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
</script>
<body>
<a id="myMagicLink" href="#">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>
Sorry it seems a bit complicated for something pretty simple, unless you have a specific design in mind; but this should work equally well:
The Fiddle
<html>
<head>
<script language="JavaScript" type="text/javascript">
var toggled = false;
function toggleDiv()
{
if(toggled)
{
document.getElementById('foo').style.display = '';
toggled = false;
}
else
{
document.getElementById('foo').style.display = 'none';
toggled = true;
}
}
</script>
</head>
<body>
<a id="myMagicLink" href="http://www.google.com/" onClick='toggleDiv()'>My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>
​

image swap in chrome extension popup

I have an image within a popup that I would like to be swapped out with another image when clicked. I check localStorage to know whether the "on" or "off" button should be displayed.
popup.html:
<body>
<div>
<img id="onOffButton" src="img/on_button.png" onclick="onOff()" />
</div>
</body>
popup.js:
function onOff() {
var onOffButton = document.getElementById("onOffButton");
if (localStorage.ToneSet === "off") {
onOffButton.src="img/on_button.png";
} else {
onOffButton.src="img/off_button.png";
}
}
Currently my localStorage.ToneSet is set to "on" so my image should flip from "on_button.png" to "off_button.png", but it continues to display on_button.png. Any idea what I'm doing wrong? Thanks.
Maybe something like this http://jsfiddle.net/EX2hj/1/
I dunno this worked for me when I created a random test.html
<div id="onOffButton" style='width:200px;height:200px;border:1px solid' onclick='toggle()'> </div>
<script>
function toggle(){
alert("a");
var onOffButton = document.getElementById("onOffButton");
if (localStorage.ToneSet == "off") {
onOffButton.style.background = "red";
localStorage.ToneSet = "on";
} else {
onOffButton.style.background = "green";
localStorage.ToneSet = "off";
}
}
toggle();
</script>

javascript button show/hide on text changed

I want to show and hide a button by using java script.
My problem is that the button should be hide on page load and when I changed the text in text box then button should be show.
thanks.....
pls, Check this page and tell if this is what you wanted.
Basically, you need to use onchange event to do whatever you want to do.
<html>
<head>
<script>
window.onload=function(){
document.getElementById("button").style.display='none';
}
function showButton(){
document.getElementById("button").style.display='block';
}
</script>
</head>
<body>
<input type="button" id="button" value="New Button"/>
Change the text in Input Box. Then Button will be show<br/><br/>
<input type="text" id="userText" value="Change the text" onchange="showButton()"/>
</body>
</html>
Try with jQuery:
$("#yourInput").bind("change", function() {
var value = $(this).val();
if (value && value.length > 0) {
// Exist text in your input
$("#yourButton").show();
} else {
$("#yourButton").hide();
}
});
For non-jQuery:
function onchangeInput() {
var value = this.value;
if (value && value.length > 0) {
// Exist text in your input
document.getElementById("yourButton").style.visibility = "visible";
} else {
document.getElementById("yourButton").style.visibility = "hidden";
}
}
window.onload = function() {
document.getElementById("yourButton").style.visibility = "hidden";
var el = document.getElementById("yourInput");
if (el.addEventListener) {
el.addEventListener("change", onchangeInput, false);
} else {
el.attachEvent('onchange', onchangeInput);
}
}
Again, don't show/hide a button, just disable it, that make the best user experience.
You could style the css to visibilty:hidden then in javascript add an event listner like this:
<script type="text/javascript">
var box = document.getElementById('box');
var textbox = document.getElementById('textbox');
textbox.addEventListener("focus",showbox,false);
function showbox() {
box.style.visibility = 'visible';
}
That would make it appear on focus but if you wanted to take it a step further you could add another event listener for a keystroke when the textbox is focused on. That would probably work.
This is to hide/show a div based on text changed in text box.
With JQuery
<script type="text/javascript">
window.onload = function () {
document.getElementById("submitdiv").style.display = 'none';
}
$(function () {
$('.Name').on('keyup change', function () {
if (this.value.length > 0) {
$('#submitdiv').show();
} else {
$('#submitdiv').hide();
}
});
});
</script>
HTML
<%:Html.TextBoxFor(m => m.FirstName, new { #class ="Name"}) %>
<div id="submitdiv">
<button type="submit" value="Submit" class="btn btn-primary pull-right value-set" id="btnLogin">Submit</button>
</div>
Try this:
<script>
function
changeButton() {
document.getElementById("changeButton").innerHTML = "Insert text for button";
document.getElementById("changeButton").removeAttribute("hidden");
}
</script>
<button hidden id="changeButton"></button>

Categories

Resources