How to change variable value when click function is called? - javascript

I want to change the check value from false to true whenever I click on the a link. So far I've not found any suggestions on how to do this
Click Me
let check = false;
document.querySelectorAll('.click').forEach(item => {
item.addEventListener('click', event => {
check = true;
});
});
console.log(check);

Your console.log() is being executed after you assign the onclick event, not after it is called - So the only thing you log is the value of checked at the very beginning of your script
I've moved the console.log() inside the function, and also added a separate button so you can confirm that the value of check has changed in the global scope
let check = false;
document.querySelectorAll('.click').forEach((item) => {
item.addEventListener('click', (event) => {
check = true;
// Check value has changed
console.log(check);
});
});
Click Me
<br>
<button style="margin-top: 10px" onclick="console.log(check);">Console.log(check)</button>

Your solution already works, you just have to move your console.log(check) to print the new value
let check = false;
document.querySelectorAll('.click').forEach(item => {
item.addEventListener('click', event => {
check = true;
// print the new value
console.log(check);
});
});
console.log(check);
Click Me

Related

change listener on 2nd click

I have a javascript code where I store an element in an array upon clicking on a button, and change the button from "+" to "-". Upon clicking the button again, I want to remove that element from the array.
I have this code. It does the first part well, but it also removes the element without clicking on the button the second time.
let favorites = []
let buttonList = document.querySelectorAll("button")
let click = 0
buttonList.forEach((button, index) => {
button.addEventListener('click', function saveFavourites() {
click++
favorites.push(products[index])
button.textContent = "-"
console.log(favorites)
if (click === 1) {
this.removeEventListener('click', saveFavourites)
}
})
button.addEventListener('click', function removeFavourites() {
click ++
let i = favorites.indexOf(products[index])
favorites.splice(i, 1)
button.textContent = "+"
console.log(favorites)
if (click === 2) {
this.removeEventListener('click', removeFavourites)
}
})
})
You're adding two separate event listeners to the same button element. Use a single event listener and toggle a boolean flag variable to keep track of whether the element should be added or removed.
let favorites = []
let buttonList = document.querySelectorAll("button")
buttonList.forEach((button, index) => {
let isAdded = false; // flag variable to track whether the element is added or removed
button.addEventListener('click', function toggleFavourites() {
if (isAdded) {
let i = favorites.indexOf(products[index])
favorites.splice(i, 1)
button.textContent = "+"
isAdded = false;
} else {
favorites.push(products[index])
button.textContent = "-"
isAdded = true;
}
console.log(favorites)
})
})
When the button is clicked, the code checks the value of isAdded and either adds the element to the favorites array or removes it.
Here is the Demo:- Codesandbox

I have to double click the follow button to functioning this is due to using click event 2 time

I am working on follow button and with the help of JavaScript I've come up with the following code.
But the problem is I have to double click the follow button to functioning this is due to using click event 2 time. I am open to better methods of solving this too.
var value = null;
const onClick = (event) => {
// event.target.id
value = event.target.id;
console.log(value);
document.getElementById(`${value}`).addEventListener('click',function(){
// console.log(value.id);
if(this.classList.contains('follow')){
this.classList.remove('follow');
this.innerHTML ="Following";
this.style.backgroundColor = 'green' ;
}else{
this.classList.add('follow');
this.style.backgroundColor = 'rgb(27,18,83)' ;
this.innerHTML="Follow";
}
})
}
window.addEventListener('click', onClick);
There is a double click event. You can check the if it satisfies your requirement.
MDN link - https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
For multiple buttons with the same function, I would give all of them the same class (e.g. "btn"). Then in JS simply get all of the elements with this class, loop over the HTMLCollection which you would get and assign each element an eventlistener. When you want to change something on the button you have to use event.target in the function:
let buttons = document.getElementsByClassName("btn");
for (btn of buttons) {
btn.addEventListener("click", (event) => {
if(event.target.classList.contains('follow')){
event.target.classList.remove('follow');
event.target.innerHTML ="Following";
event.target.style.backgroundColor = 'green' ;
}else{
event.target.classList.add('follow');
event.target.style.backgroundColor = 'rgb(27,18,83)' ;
event.target.innerHTML="Follow";
}
});
}
<button class="btn">1</button>
<button class="btn">2</button>

Can I check if a JavaScript function is called from a button's onclick attribute?

I have a JavaScript function that can be called either from a button click or from another function.
I am working on a simple game made with vanilla JavaScript and I have a function as below:
function end() {
// End the game
}
which can be called from a button click:
<input type="submit" id="endBtn" value="End Game" onclick="end()">
and can also be called from another JavaScript function:
function play() {
// Game logic
end();
}
The game can be ended by either the user clicking on the button or if certain conditions in the play() function are met.
Is it possible to know if the function is called from a button click?
As by default functions called from events are automatically passed an event value, you can check to see if the event value is not equal to undefined. Code example:
function yourFunction(event = undefined) {
if (event && typeof(event) == "object") {
alert("Called from element")
} else {
alert("Not called from element")
}
}
yourFunction()
<button onclick="yourFunction(event)">Click me!</button>
Yes, it's possible to assess whether it was called from a button click, see below:
btn = document.getElementById("btn");
testDiv = document.getElementById("testDiv");
btn.addEventListener("click", () => {
const payload = "called from button";
randomFn(payload);
});
function randomFn(getInput) {
testDiv.innerHTML = getInput;
}
<button id="btn">Click</button>
<div id="testDiv"></div>
Just let the function accept a string like "calledBy", like:
function myEvent(calledBy){
if(calledBy=="button") //It has been called by the button
else //It has been called by function
}
In your other function you pass "func" as parameter, while in the button you pass "button"
function secondFunction(){
//Do Stuff
myEvent("func");
}
In your button:
...onClick=myEvent('button')...
Hope to be clear, there might be other solutions, but this is the first thing that came in my mind.
One way to get this is by adding another parameter to the function that will allow you to differentiate the source. I.e. if you have a function
function abc(argument1) {
//logic
}
You could add
function abc(argument1, argument2){
if (argument2 === 'button' {
//some logic
}
//logic
}
If you call it from the button, you can call it with onClick: () => abc(argument1, 'button') so you know it came from the button. If called elsewhere, you would change the argument provide from 'button' to whatever you like.
the this in the element onclick will pass the element itself
so you can check if it's an element or not
function test(ele) {
if (ele instanceof Element) {
console.log("this is call by click button");
} else {
console.log("this is call by other way");
}
}
test();
<button onclick="test(this)">ckick me</button>
Actually there may be a workaround. Give your function a string parameter for ex $notifier.
When calling from button click give $notifier parameter as 'button' or whatever meaningful.
So from there by checking the parameter value you can get to know from where the function is fired.
function myFunction(notifier){
if (notifier=='button'){
// triggered from button
}
else if(notifier=='function'){
// triggered from function
}
}
and on button -> onclick="myFunction('button')"
I am not exactly sure what you are trying to do. However, if you truly must log/check if it was a button click or called from another function, you can do something like this:
function triggerFromFunction(d) {
triggerClick(true);
}
function triggerClick(comingFromFunction = false) {
document.getElementById("show").innerHTML = 'Coming from Function = ' + comingFromFunction;
}
<button onclick="triggerClick()">Trigger Click</button>
<button onclick="triggerFromFunction()">Trigger Function</button>
<p id="show"></p>
This solution is based on ES2015. Otherwise you can check if parameter is undefined in an if statement and proceed from there. Checkout:
https://www.w3schools.com/howto/howto_js_default_parameters.asp
All you need to do is look at the function parameters, specifically event.type, which all events will pass, if it has no params it must have been called directly (though you can pass a type if you wanted)
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", theFunction);
button.addEventListener("mouseover", theFunction);
button.addEventListener("mouseout", theFunction);
function theFunction(e) {
if (e && e.type) result.innerHTML = 'from ' + e.type
else result.innerHTML = 'has no type, perhaps theFunction()'
}
theFunction({type: 'foo'})
<button id="button">Click</button>
<div id="result"></div>

How to know if we are leaving web page?

I have a form on my page. If it is changed because beforeunload event the user will have a dialog which catch the leave process.
If the user click on "continue" or "leave" then the new page is loading and form's data are lost.
If the user click on "cancel" the leave process is canceled.
How can we know when the user has clicked on cancel ?
Why I need to know that ?
In my case I have a switch button. When the user turns it on, the script tries to reload the page. If the user click on "continue" or "leave" it's ok. But if the user click on "cancel" I would like show back the switch on the position "off".
When a user changes the button position ON and then attempts to leave but then cancel, the state of the button should change to OFF. We can use window.onbeforeunload function and returning false within the block of its code. Please see the below example, note that I have used checkbox instead of toggle switch, but you can type anything inside the window.onbeforeunload function to your desire.
window.onbeforeunload = () => {
document.getElementById("checkbox").checked = false;
return false;
}
.checkbox {
margin-top: 20px;
margin-left: 20px;
}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>
<div>
Click here to exit this site and go to google.com
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox">
</div>
To handle the state of the button, we can use localStorage and setInterval timer to check if the user has left the site and onbeforeunload event to prompt user to leave or cancel. When user cancels, the interval counts down to 0, this means the user is still on your site and updates the localStorage, but if left, the interval will not continue and doesn't change the localStorage value, and therefore, when returning to your site, the checked button should be updated to the previous position. Note that, when you click Run code snippet on this site, it might not work for localStorage, run this code from your site or on JSFiddle. :-)
window.onload = () => {
// declaration & Initialization
const input = document.createElement("input");
const defaultCounterValue = 10; // incremental --
const defaultIntervalValue = 50; // ms
const checkbox = document.getElementById('checkbox');
const setLocalStorage = (itemName, itemValue) => {
localStorage.setItem(itemName, itemValue);
};
const getLocalStorage = (itemName) => {
return localStorage.getItem(itemName) === null ? false : localStorage.getItem(itemName) === 'false' ? false : true;
};
let interval = undefined;
let counter = defaultCounterValue;
setLocalStorage('checkbox', getLocalStorage('checkbox').toString());
setTimeout(() => {
checkbox.checked = getLocalStorage('checkbox');
}, 0);
checkbox.addEventListener('click', () => {
setLocalStorage('checkbox', checkbox.checked);
});
// set input property and event handlers
input.type = 'checkbox';
input.checked = false;
input.style.display = 'none';
input.addEventListener('click', () => {
let removeInterval = () => {
clearInterval(interval);
interval = undefined;
}
if (interval) {
removeInterval();
}
interval = setInterval(() => {
if (input.checked === true) {
if (counter === 0) {
checkbox.checked = false;
setLocalStorage('checkbox', checkbox.checked);
counter = defaultCounterValue;
input.checked = false;
}
counter--;
} else {
removeInterval();
}
}, defaultIntervalValue);
});
document.body.appendChild(input);
// Event that run before the user leaves
window.onbeforeunload = (event) => {
event.preventDefault = true;
event.cancelBubble = true;
event.returnValue = null;
input.checked = false;
input.click();
};
}
.checkbox {
margin-top: 20px;
margin-left: 20px;
}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>
<div>
Click here to exit this site and go to google.com
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox">
</div>

How to modify outside variable from inside an event handler in javascript?

I have a button with a click event listener
let button = document.createElement('button');
let show = false;
button.addEventListener('click', (e) => {
e.stopPropagation();
show = !show;
console.log("show from inside:", show)
});
console.log("show from outside:", show) // => is always equal to false
But this line above still shows the same value for variable show as initialized.
How can i modify show variable from inside like this line show = !show and get that modification from outside at this line console.log("show from outside:", show) ?
You have created the element but did not append it to body/parent node. You need to add the following line to your code.
document.body.appendChild(button);
If you need to get the modified show value, you can write a function to return the value of show and use it whereever you want.
Final Code:
let button = document.createElement('button');
document.body.appendChild(button);
let show = false;
function getShow() { return show; } // => returns the latest value of show
button.addEventListener('click', (e) => {
e.stopPropagation();
show = !show;
console.log("show from inside:", getShow());
});
console.log("show from outside:", getShow()); // => Keep in mind that this line will run before the event handler does and only for once.
Hope this helps!

Categories

Resources