Button that acts like toggle with JS functions - javascript

How can I make a HTML button act like a toggle? I have two JS functions that modify an image, one to a new image and the other to change it back. How can I make sure a button activates the first function when pressed the first time but then activates the second when pressed again, repeated for the third and fourth time etc.
document.getElementById("baseImg").src = "assets/1stImg.png";
function imgChange1() {
document.getElementById("baseImg").src = "assets/2ndImg.png";
}
function imgBack1() {
document.getElementById("baseImg").src = "assets/1stImg.png";
}
<img id="baseImg">
<button onclick="imgChange1()">Change</button>
How would I go about including the second function within this button?
`

I don't really get your question because you were saying "toggle" but you were saying
How can I make sure a button activates the first function when pressed
the first time but then activates the second when pressed again?
But well, here's how you do it:
var clicked = false;
function toggleBtnClick(button) {
var img = document.getElementById('baseImg');
if (clicked) { //this will be executed on future clicks after first click
img.src = 'http://via.placeholder.com/350x150/4CAF50/000000';
console.log('Next click');
//or do something else
} else { //this will only be executed once
img.src = 'http://via.placeholder.com/350x150/e9e9e9/000000';
console.log('First click');
}
clicked = true; //update to true after first click
}
button {
position: absolute;
right: 0;
}
<img id="baseImg" src="http://via.placeholder.com/350x150/3fafed/000000">
<button onclick="toggleBtnClick()">Change</button>
But, if you really want a "toggle" functionality, here's how you do it:
var clicked = false;
function toggleBtnClick() {
var img = document.getElementById('baseImg');
if (clicked) {
img.src = 'http://via.placeholder.com/350x150/e9e9e9/000000';
clicked = false;
} else {
img.src = 'http://via.placeholder.com/350x150/3fafed/000000';
clicked = true;
}
}
button {
position: absolute;
right: 0
}
<img id="baseImg" src="http://via.placeholder.com/350x150/e9e9e9/000000">
<button onclick="toggleBtnClick()">Change</button>

Related

Basic Javascript click function not loading

I am just trying to change the font attribute via a click function real beginner stuff, however I want to check if the element has been clicked a second time and do something if so.
var clicks = 0;
document.getElementById('button2').click(function(){
clicks++;
if(clicks%2===0){
document.getElementById('demo2').style.fontSize='22px';
} else{
document.getElementById('demo2').style.fontSize='12px';
}
});
What am i doing wrong?
Why not using an event listener instead?
According to the mozilla documentation (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click), the click function does not expect a function that defines the behavior of the click.
Try the following:
var clicks = 0;
document.getElementById('button2').addEventListener('click', function(){
clicks++;
if(clicks%2===0){
document.getElementById('demo2').style.fontSize='22px';
} else{
document.getElementById('demo2').style.fontSize='12px';
}
});
<button id="button2">Click me</button>
<div id="demo2">Hello</div>
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/onclick
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
.click fires a click, it doesn't watch for them
var clicks = 0;
document.getElementById('button2').onclick = function(){
clicks++;
console.log(clicks)
if(clicks%2===0){
document.getElementById('demo2').style.fontSize='22px';
} else{
document.getElementById('demo2').style.fontSize='12px';
}
};
<div id="button2">button2</div>
<div id="demo2">demo2</div>
This is what you should do though just toggle a class look how much code is removed and it does the exact same thing :)
const button = document.querySelector('.button2');
const demo = document.querySelector('.demo2');
button.addEventListener('click', () => demo.classList.toggle('large'));
.demo2 {
font-size: 12px;
}
.large {
font-size: 22px;
}
<div class="button2">button2</div>
<div class="demo2">demo2</div>

Setting onclick on parent results on parent executing onclick without intention Javascript

I have a layout which I dont think its necessary to post here. But its basically a parent div with a very small width and height that stays on bottom right of a page, if clicked on it, it enlarges width and height.
Here where I had issue:
The parent contains onclick, if its click, it then change its size as well as disabling its onclick and adding onclick to an image, which is a button to minimise the parent div to its original size.
If the image is clicked then again, I disable the onclick on the image and add onclick on the main parent. However Javascript is executing onclick on the parent as it thinks its been clicked, since the image is inside the parent.
To fix this issue I had to set a setTimeout to add the onclick to the parent, that solved the issue, but is there a better way, and why does that happen?
Tahnks
function adjust_window_displayed(el, main_el){
var val = el.value;
var img_el = document.getElementById("img_envelope");
if(val === "true"){
document.getElementById("display_mail_info").style.display = "block";
img_el.src = "https://co.uk/minimise.png";
img_el.style.cursor = "pointer";
main_el.style.cursor = "default";
main_el.onclick = function () {
return false;
};
el.value = "false";
img_el.onclick = function () {
adjust_window_displayed(el, main_el);
console.log("first");
};
console.log("first " + main_el.className);
}else{
document.getElementById("display_mail_info").style.display = "none";
img_el.src = "https://dco.uk/envelope.png";
img_el.style.cursor = "default";
main_el.style.cursor = "pointer";
el.value = "true";
img_el.onclick = function () {
return false;
};
setTimeout(function() {
main_el.onclick = function () {
adjust_window_displayed(el, main_el);
console.log("sec");
};
}, 700);
console.log("second " + main_el.className);
}
}
What happens is due to the event bubble, when you click on the <img> the click event fire once, then a second time for the parent, now if you don't handle that in your function properly it'll give you problems.
Now I have no idea how you're calling that function nor what parameters, you're passing to it, so i tried to reproduce the problem myself.
If you would assign the click event useing the .onclick = function(){}
you can use it to alter between the two, since you're using the same function.
document.querySelector('#parent').onclick = lol;
function lol(e){
var type = e.target.nodeName;
if (type == "DIV")
{
if (e.target.onclick)
{
alert('clicked parent');
e.target.onclick = "";
document.querySelector('#kid').onclick = lol;
}
}
else if (type == "IMG")
{
if (e.target.onclick)
{
alert('clicked kid');
e.target.onclick = "";
document.querySelector('#parent').onclick = lol;
}
}
}
#parent{
width: 500px;
height: 500px;
background-color: red;
}
img{
width: 10%;
height: 10%;
}
<div id="parent">
<img id="kid">
</div>

Toggle Event Listeners

I am trying to make a function that would allow me to toggle eventListener of an element.
In the example below, I have three buttons: main, on and off. When I click on the on button, the main button becomes functional. After I click off button, the main button should not work anymore (but now it still does).
Now I can achieve a desired behavior by clicking on button for the second time, but I guess it's a bad coincidence and it's not supposed to work that way.
Maybe I should add that I would like to work this out without using jQuery or similar and it needs to be a function, because I am going to use it for a lot of buttons.
(I suspect something with scope causes the problem (clickHandler when calling the function to activate the button is not the same as the clickHandler when calling the function to disable the button), but I can't think of a way to test it.)
// buttons definitions, not important
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButton = document.querySelector("#offButton");
// main function
var toggleButtons = function(toggleVal, button, element) {
var activateButton, clickHandler, disableButton;
// callback function for listener bellow
clickHandler = function() {
document.querySelector(element).classList.toggle("yellow");
};
activateButton = function() {
button.addEventListener("click", clickHandler);
};
disableButton = function() {
button.removeEventListener("click", clickHandler);
};
// when first argument is 1, make the button functional, otherwise disable its functionality
if (toggleVal === 1) {
activateButton();
} else {
disableButton();
}
};
// when onButton is clicked, call main function with arguments
// this works
onButton.addEventListener("click", function() {
toggleButtons(1, mainButton, "body");
});
// this fails to disable the button
offButton.addEventListener("click", function() {
toggleButtons(0, mainButton);
});
.yellow {
background-color: yellow;
}
<button type="button" id="mainButton">mainButton
</button>
<button type="button" id="onButton">onButton
</button>
<button type="button" id="offButton">offButton
</button>
<p>mainButton: toggles background color on click
</p>
<p>onButton: turns on mainButtons's functionality</p>
<p>offButton: supposed to turn off mainButton's functionality</p>
var mainButton = document.querySelector("#mainButton");
var onButton = document.querySelector("#onButton");
var offButon = document.querySelector("#offButton");
var element; // declare the element here and change it from toggleButtons when needed.
function clickHandler() {
document.querySelector(element).classList.toggle('yellow');
}
function activateButton(button) { // You missed this part
button.addEventListener('click', clickHandler);
}
function disableButton(button) { // You missed this part
button.removeEventListener('click', clickHandler);
}
function toggleButtons(value, button) {
if (value === 1) {
activateButton(button); // You missed this part
} else {
disableButton(button); // You missed this part
}
};
onButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(1, mainButton);
});
offButton.addEventListener('click', function() {
element = 'body'; // you can change it to some other element
toggleButtons(0, mainButton);
});
Below code helps to toggle between two functions from an eventListener:
var playmusic=false;
function playSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.currentTime = 0
audio.play()
playmusic=true;
}
function stopSound() {
const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
audio.pause()
playmusic=false;
}
window.addEventListener('keydown',
function(){playmusic?stopSound():playSound()} )

add1 does not exist in DOM How to Add?

I am having an issue with java-script and an HTML form.
I have a form and next to the form is a button called "add" when I click add the second form appears. Next to form 2 is another button called add1, when I click this button I am wanting the third form to display. For some reason only the first add button is working.
Below is the code I have so far:
<style type="text/css">
#newservicesetup1, #newservicesetup2 {
display:none;
}
</style>
<script type="text/javascript">
function showform(theform) {
var showHides = new Array('newservicesetup1','newservicesetup2');
for (i=0;i<showHides.length;i++) {
document.getElementById(showHides[i]).style.display=
(document.getElementById(showHides[i]).id == theform) ? 'block' : 'none';
}
}
function loadBehaviors () {
if (document.getElementById) {
document.getElementById('add').onclick = function() { showform('newservicesetup1'); }
document.getElementById('add1').onclick = function() { showform('newservicesetup2'); }
}
}
window.onload = loadBehaviors;
</script>
Try adding a semicolon to the end of the assignments:
function loadBehaviors () {
if (document.getElementById) {
document.getElementById('add').onclick = function() { showform('newservicesetup1'); };
document.getElementById('add1').onclick = function() { showform('newservicesetup2'); };
}
}
You can check your Javascript for syntax using Online Javascript Lint.
why not just
document.getElementById('add').onclick = function() {
document.getElementById('newservicesetup1').style.display = 'block';
}
document.getElementById('add1').onclick = function() {
document.getElementById('newservicesetup1').style.display = 'block';
}
that will show the correct forms when you click the appropriate button. if you want them to disappear when clicking again, you will only need a slight modification
When loadBehaviors() is called, add1 does not exist in the DOM yet. Bind to the event handler after you add it to the DOM.

Changing HTML on click in D3.js disables doubleclick [duplicate]

I've toggled click event to a node and I want to toggle a dbclick event to it as well. However it only triggers the click event when I dbclick on it.
So How do I set both events at the same time?
You have to do your "own" doubleclick detection
Something like that could work:
var clickedOnce = false;
var timer;
$("#test").bind("click", function(){
if (clickedOnce) {
run_on_double_click();
} else {
timer = setTimeout(function() {
run_on_simple_click(parameter);
}, 150);
clickedOnce = true;
}
});
function run_on_simple_click(parameter) {
alert(parameter);
alert("simpleclick");
clickedOnce = false;
}
function run_on_double_click() {
clickedOnce = false;
clearTimeout(timer);
alert("doubleclick");
}
Here is a working JSFiddle
For more information about what delay you should use for your timer, have a look here : How to use both onclick and ondblclick on an element?
$("#test-id").bind("click dblclick", function(){alert("hello")});
Works for both click and dblclick
EDIT --
I think its not possible. I was trying something like this.
$("#test").bind({
dblclick: function(){alert("Hii")},
mousedown: function(){alert("hello")}
});
But its not possible to reach double click without going through single click. I tried mouse down but it does not give any solution.
I pretty much used the same logic as Jeremy D.
However, in my case, it was more neat to solve this thing with anonymous functions, and a little slower double click timeout:
dblclick_timer = false
.on("click", function(d) {
// if double click timer is active, this click is the double click
if ( dblclick_timer )
{
clearTimeout(dblclick_timer)
dblclick_timer = false
// double click code code comes here
console.log("double click fired")
}
// otherwise, what to do after single click (double click has timed out)
else dblclick_timer = setTimeout( function(){
dblclick_timer = false
// single click code code comes here
console.log("single click fired")
}, 250)
})
you need to track double click and if its not a double click perform click action.
Try this
<p id="demo"></p>
<button id='btn'>Click and DoubleClick</button>
<script>
var doubleclick =false;
var clicktimeoutid = 0;
var dblclicktimeoutid = 0;
var clickcheck = function(e){
if(!clicktimeoutid)
clicktimeoutid = setTimeout(function(){
if(!doubleclick)
performclick(e);
clicktimeoutid =0;
},300);
}
var performclick =function(e){
document.getElementById("demo").innerHTML += 'click';
}
var performdblclick = function(e)
{
doubleclick = true;
document.getElementById("demo").innerHTML += 'dblclick';
dblclicktimeoutid = setTimeout(function(){doubleclick = false},800);
};
document.getElementById("btn").ondblclick = performdblclick;
document.getElementById("btn").onclick=clickcheck;
</script>
a slightly different approach - The actual click comparison happens later in the timeOut function, after a preset interval... till then we simply keep tab on the flags.
& with some simple modifications (click-counter instead of flags) it can also be extended to any number of rapid successive clicks (triple click, et al), limited by practicality.
var clicked = false,
dblClicked = false,
clickTimer;
function onClick(param){
console.log('Node clicked. param - ',param);
};
function onDoubleClick(param){
console.log('Node Double clicked. param - ',param);
};
function clickCheck(param){
if (!clicked){
clicked = true;
clickTimer = setTimeout(function(){
if(dblClicked){
onDoubleClick(param);
}
else if(clicked){
onClick(param);
}
clicked = false;
dblClicked = false;
clearTimeout(clickTimer);
},150);
} else {
dblClicked = true;
}
};

Categories

Resources