How to call different JS functions on different clicks on a button? - javascript

I am trying to call a JS function that triggers a popup on the first click of the button after page load. And then a different function on the second click, I have no idea how to make that work and anything I've found on it has been difficult to adapt.
This is the popup: https://jsfiddle.net/d80tcw5f/
Below is the element for the current button.
<a ng-class="{true : 'cart-checkout-button disabled', false : 'cart-checkout-button'}[data.DisableCheckout]" ng-click="PlcaOrder()" >
<span class="payment-label">{{data.PlaceOrderText}} </span>
<span aria-hidden="true" class=" icon-arrow-right2"></span> </a>
"PlcaOrder()" is the function that redirects to the payment gateway, which I need to happen on the second click.
Any help would be very much appreciated, thanks!

The way to do it would be to create a 3rd function for routing
var func1 = ...;
var func2 = ...;
var func3 = function(e) {
if (!this.firstClick) {
this.firstClick = true;
func1(e);
} else {
func2(e);
}
}

At the end of the function that gets called on the first click just change the value of the ng-click attribute to the second function that you want calling e.g. PlcaOrder()

Im not sure if I get your point correctly but try somthing like setting a boolean on the click event. Once you click on the button, set it to true, then call to second function (set the second function to be called only if your boolean is set to true). Then after the second function call, reset the boolean back to false.

I would store the number of clicks in a variable and then increment that number every time the button is clicked. Then, depending on the number of the variable do something. Example:
let clicks = 0;
function myFunction() {
clicks++;
if (clicks === 1) {
console.log("button clicked for the first time")
} else {
console.log("button clicked more than once")
}
}
<button onclick="myFunction()">Click me!</button>

Switch style.
var clicks = 0;
function clickSwitcher() {
switch (clicks) {
case 0:
console.log("click0", "Do something!");
break;
case 1:
console.log("click1", "Make a thing.");
break;
case 2:
console.log("click2", "Drink!");
break;
case 3:
console.log("click3", "Test the loop.");
break;
case 4:
console.log("click4", "Sleep.");
clicks = 0 //and restart
break;
}
clicks++;
}

Related

How do i make a like button that increase counter on first click and decrease on second click

I'm trying to make a like button that counts and decreases just like the typical social media like button
I came up with this js but it just keeps decreasing when clicked.
and I would really appreciate it if I could get help on how to store the counts on my website
function liked(heart){
heart.classList.toggle("liked");
if (heart.liked) {
click ++;
} else {
click --;
}
document.getElementById('clicks').innerHTML = click;
}
Since you didn't give us all your revelant code I'm going to assume some things but you can still use it to help you mimic a like/dislike behaviour
In this example I have 2 buttons a like and a dislike button and both of them call the same function.
<h1 id="counter">10</h1>
<button id="like" onclick="liked(event)">like</button>
<button id="dislike" onclick="liked(event)">dislike</button>
Usually when you click like the common behaviour is counter +1 but the user can also unlike the post or the video, whatever by pressing the button again. Same goes for the dislike button which has a counter-1 behaviour but you can also press it again to return the counter back to what it was before.
You can only have 3 options tho:
Like it = counter+1
dislike it = counter-1
neither of them = counter unchanged
With this code, if like button was pressed and you switch to dislike then the counter will decrease by 2 since it removes the like state you gave it or it can be the other way around and go up by 2 if you go from dislike to like
let like_flag = false;
let dislike_flag = false;
function liked(event) {
let counter = parseFloat(document.getElementById('counter').innerHTML);
var button = event.target.innerText;
switch(button){
case 'like':
if (like_flag==false && dislike_flag==false) {
counter++;
like_flag=true;
} else if (like_flag==false && dislike_flag==true) {
counter = counter + 1; //changed this to 1 instead of 2
like_flag=true;
dislike_flag=false;
} else {
counter--;
like_flag=false;
}
break;
case 'dislike':
if (dislike_flag==false && like_flag==false) {
counter--;
dislike_flag=true;
} else if (dislike_flag==false && like_flag==true) {
counter = counter - 1; //changed this to 1 instead of 2
dislike_flag=true;
like_flag=false;
} else {
counter++;
dislike_flag=false;
}
break;
}
console.log('the button '+button+' was pressed');
document.getElementById('counter').innerHTML = counter;
}
Since both buttons call same function then we use flags and change them from false to true or from true to false. That way we know what button was pressed and what our code should do next. Hope this helps
https://jsfiddle.net/kenpy/p8oesf61/53/
classList.toggle() return a boolean value
so, simply do:
function liked(heart)
{
if (heart.classList.toggle('liked') ) click++;
else click--;
document.getElementById('clicks').textContent = click;
}

Element disappearing before it is supposed to

Recently I've been coding a clicker game and now have run into a problem with the onclick function. What I'm trying to do is on the first click, have it change into certain text, and on the second and third clicks change it to a different text. However, on the fourth click, I'd like it to disappear.
However, it disappears on the third click instead of the fourth click. The third click is supposed to show more text, and then call a function and vamoose. It just disappears. Here is my code:
function change_text(){
let first_click = true;
onclick = function() {
if (first_click) {
document.getElementById("speech").innerHTML = "You will? Thanks so much! Let's make our first pastry. Click the pastry!";
first_click = false;
}
else {
document.getElementById("speech").innerHTML = "Wow, that looks amazing! It make take a while to bake them all by hand; so when you want to go faster, head to the shop and buy upgrades! Have fun!";
function second_click(){
document.getElementById("speech").outerHTML = ""
}
document.getElementById("speech").onclick = second_click();
}
}
What can I do?
I'm going to rewrite your code because it seems to be missing something.
In this code, I'm using a single event handler. Then using a counter and switch statement to determine the current click count.
let speech = document.querySelector("#speech");
let clicks = 1;
speech.addEventListener("click",function(){
speech.style.display = "block";
switch(clicks){
case 1: speech.innerHTML = "You will? Thanks so much! Let's make our first pastry. Click the pastry!";break;
case 2: speech.innerHTML = "Wow, that looks amazing! It make take a while to bake them all by hand; so when you want to go faster, head to the shop and buy upgrades! Have fun!";break;
case 3: speech.innerHTML = "3 text!!";break;
case 4: speech.innerHTML = "";speech.style.display = "none";clicks=0;break;
}
clicks++;
});
#speech{background:red;cursor:pointer;}
<div id="speech">CLICK HERE</div>
Try something like that.
var clicks = 0;
function change_text(){
clicks += 1;
console.log("Action " +clicks)
if (clicks === 1) {
//do something
} else if (clicks === 2) {
//do something
} else if (clicks === 3) {
//do something
} else if (clicks === 4) {
//do something
}
}
<button onclick="change_text()">Click me</button>
Your code is difficult to understand. Just an advice, try to organize your logic before write code and try to code in a simple way like this:
const speeches = ["You will? Thanks so much! Let's make our first pastry. Click the pastry!'", "Wow, that looks amazing! It make take a while to bake them all by hand; so when you want to go faster, head to the shop and buy upgrades! Have fun!", "Third speech"];
const speech = document.getElementById("speech");
let clickCounter = 0;
speech.addEventListener("click", function() {
if (clickCounter >= speeches.length) {
clickCounter = 0;
speech.style.display = 'none';
return;
}
speech.innerHTML = speeches[clickCounter];
clickCounter++;
});
<div id="speech">CLICK ME!</div>

Toggle text in button onclick

I'm trying to toggle the text in a button every time it's clicked, between "READ" and "NOT READ". The buttons have been created dynamically with js and placed into an HTML table. Each button has a unique ID, but the same class name.
I've written an if statement that works for the first button that is set in the table, but the same if statement wont work for the buttons created dynamically.
I've tried lots of different variations for the if statements. I'm not sure if the best way would be to access the unique id's, but I don't know how to do that.
Any help is appreciated! Thanks
Here's a repl https://repl.it/repls/SpryVisibleMining
function toggleText(){
if (readButton.innerHTML == "READ"){
readButton.innerHTML = "NOT READ";
} else if (readButton.innerHTML == "NOT READ"){
readButton.innerHTML = "READ";
} else {
null
}
}
And this is if statement that wont wont do anything
function toggleOthers() {
let toggle = document.getElementsByClassName(".readBtn")
toggle[0].addEventListener("click", () => {
if (toggle.innerHTML == "READ") {
toggle.innerHTML = "NOT READ"
} else if (toggle.innerHTML == "NOT READ") {
toggle.innerHTML = "READ"
} else {
null
}
})
}
toggleOthers()
The problem lies in how you are listening for the click events. Your toggleText function is triggered whenever you click the #readed button with the onclick attribute. But inside the toggleText function you add another event listener to the same button, adding a new event listener every time you click the button.
So every time you click the button you increment the amount of times you are calling toggleText.
Remove the onclick from the button and change the id to a class attribute. You said you would have multiple buttons, so having multiple buttons with the same id won't do it.
<button class="readed">READ</button>
Because you want to listen for the click event on dynamically created elements I suggest you use Event Delegation. This means listening for the click event on a parent element, this could be your table#shelf element, and check which element has been clicked. If A has been clicked, then do X, if B has been clicked, then do Y.
Listen for click event on your table element.
var table = document.getElementById('shelf');
table.addEventListener("click", tableClickHandler);
In tableClickHandler check which element has been clicked. You can do it by getting the clicked target and use the closest method to see if it really is the element you want to be clicked.
For example when you would have a <span> in your <button>, event.target would be <span>. But you want the <button> element. closest goes up in the DOM tree to see if it finally reaches an element that is the <button> you want and returns it.
You can do this for any button inside of your table.
function tableClickHandler(event) {
var readed = event.target.closest('.readed');
if (readed) {
toggleText(readed);
}
}
Modify your toggleText function so that it can take any <button> you throw add it that you want the text toggled in. Add a button parameter which represents the current button.
// Toggle text when clicked.
function toggleText(button) {
if (button.innerHTML == "READ") {
button.innerHTML = "NOT READ";
} else if (button.innerHTML == "NOT READ") {
button.innerHTML = "READ";
} else {
null
}
}
For example you can use this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="toggle(this)">not read</button>
<script>
function toggle(e) {
let txt = e.innerText;
e.innerText = txt == 'not read' ? 'read' : 'not read';
}
</script>
</body>
</html>
Let me know if it's not suitable for your use case ...
And also you can use querySelectorAll() to get all buttons and then set this event with a for() loop.
Try
toggleText = b=> b.innerHTML = b.innerHTML=='READ'?'NOT READ':'READ'
<button id="A" onclick="toggleText(this)">NOT READ</button>
<button id="B" onclick="toggleText(this)">NOT READ</button>
According to your repl, you also registered an onclick-Handler on your button, too.
So calling toggleText() while clicking the "Read/Not-Read"-button, will effectively register another onclick-Handler. This will repeat as often as you press the button.
This will run as follows:
run onclick-Handler toggleText(); this will register another EventListener
run the EventListener (registered first by index.js)
run the new registered EventListener (registered by button.onclick)
rinse and repeat ...
Just remove it in your HTML:
<td><button id="readed">READ</button></td>
You have to init an array named books, and each time you add a new book, you have to push the new book to the books array.
And also you have to set a flag as hasReadBook to the Book class.
When you are going to render your table row you have to write an if, for making the flag to string in dom.
function updateTable() {
//anythings needs to done for updating table.
//for hasReadBook flag you should do like this:
const hasReadBookString = books[i].hasReadBook ? "Read" : "Not Read";
}
And you need to make a loop on readBtn HTML collection, to know which index is going to change:
let books = [{...}];
let toggles = document.getElementsByClassName(".readBtn");
for (var i = 0; i < toggles.length; i++){
labels[i].addEventListener('click', function(e) {
books[i].hasReadBook = !books[i].hasReadBook;
})
}
updateTable();

How to turn on/off a function on a button click?

I have been working in a mini-game-project (Simons game) that many of you may know. Where the computer plays a random sequence of buttons in which players have to follow to go to the next level in the game e.g: [one click first round, two clicks second round..].
I already did all the button effects as well as make the machine plays buttons randomly in a range of ten rounds. So, what I would like to do is use a button to turn on and off the function that makes the computer clicks By Itself using a button.
I already tried using the jQuery function $(startButton).on('click', clickByItself); alone but it did not worked.
$(document).ready(function() {
//four variables representing its button effects
//button blue effect
var blueButtonEffect = code here;
var greenButtonEffect = code here;
var redButtonEffect = code here;
var yellowButtonEffect = code here;
//to be used on the buttonEffects()/clickByItself()
var arr = [blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect];
let enabled = true;
let times = 0;
//makes button effects play itself randomly
function clickByItself() {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
if (++times < 10) {
setTimeout(function() { clickByItself(times); }, 1000);
}
}
clickByItself();
function turnOnTurnOff() {
if (enabled == true) { //TRYING TO TURN ON/OFF THE FUNCTION ON BUTTON CLICK..
$(startButton).on('click', clickByItself);
}else{
$(startButton).on('click', clickByItself);
}
}
Now, I am trying to use a function turnOnTurnOff() to see whether I could do the effect of turning on and off with the click of a the startButton. Thank you.
You can use .off() method of jQuery to remove an event listener as follows.
I added two divs for better demonstration.
One button binds and unbinds (toggles) the click handler of the second button using jQuery's .on() & .off(). When the click handler is bound to the second button, clicking it will update the div with a number. When the click handler is unbounded from the second button, clicking the second button will do nothing. Two lines of interest in the JavaScript code below are decorated with a comment each. The rest is for demonstration.
window.enabled = false;
window.count = 1;
// Initialize the view (for demo)
$(function() {
$('#switchIndicator').html(`<p>${enabled ? 'Switch is ON' : 'Switch is OFF'}</p>`);
$('#btn').html(enabled ? 'You can click me :-)' : 'You CANNOT click me');
});
// Toggle click functionality using jQuery's .on() & .off() methods
function toggle() {
enabled = !enabled;
if (enabled) {
// Line of interest #1: jQuery .on()
$('#btn').on('click', handleClick);
} else {
// Line of interest #2: jQuery .off()
$('#btn').off('click', handleClick);
}
$('#switchIndicator').html(`<p>${enabled ? 'Switch is ON' : 'Switch is OFF'}</p>`);
$('#btn').html(enabled ? 'You can click me :-)' : 'You cannot click me :-((');
$('#btn').removeClass(enabled ? 'disabled' : 'enabled').addClass(enabled ? 'enabled' : 'disabled');
}
function handleClick() {
$('#counter').append(` ${count++}`);
}
/* CSS */
#btn.enabled {
background-color: greenyellow;
}
#btn.disabled {
background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="switchIndicator"></div>
<button id="switch" onclick="toggle()">On/OFF Switch</button>
<button id="btn"></button>
<div id="counter"></div>
Give this a try:
function clickByItself() {
if(enabled) {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
if (++times < 10) {
setTimeout(function() { clickByItself(times); }, 1000);
}
}
}
clickByItself();
function turnOnTurnOff() {
if (enabled) {
enabled = false;
} else {
enabled = true;
clickByItself();
}
}
$(startButton).click(function() {
turnOnTurnOff();
});
You could do it in multiple ways. One is to use setInterval instead of setTimeout and store it inside a variable. When you need to stop it, just call clearInterval.

Array resets with every keyup

More specifically, what I am wanting to do is - with each hit of the enter key, the user is presented a famous quote (my switch/cases). Once they have toggled through the list (finished off the array), they will have the option to do it again (hit the ‘yes’ button). Once the yes button is pressed, the user toggles through the array again until its end is reached. (Then they have the option to do it all again, if desired). The problem occurs when I wrap the code in a function to make a call to that function with a button click. I can’t seem to recreate the process of toggling through my entire array to the finish. As mentioned, what is happening is that the array is created again and again with each hit of the enter key. Any thoughts?
<body>
<p id='show'>When enter button pressed, <br>random case selections are<br>shown here until array emptied.</p>
<button onclick="myFunction()">When clicking this button, I am wanting<br>the same response from the function call,<br>
but my event listener keeps resetting my array. How to prevent that? </button>
<script>
myFunction();
function myFunction() {
var casesDrawn = [0, 1, 2];
document.body.addEventListener('keyup', function(e) {
if (e.keyCode == 13 && casesDrawn.length > 0) {
randSelect();
}
function randSelect() {
var randNum = Math.floor(Math.random() * casesDrawn.length);
var num = casesDrawn[randNum];
casesDrawn.splice(randNum, 1);
switch (num) {
case 0:
document.getElementById('show').innerHTML = 'case 1 selected';
break;
case 1:
document.getElementById('show').innerHTML = 'case 2 selected';
break;
case 2:
document.getElementById('show').innerHTML = 'case 3 selected';
break;
}
}
});
}
</script>
</body>
Whenever you call myFunction() when the button is clicked, this line executes:
var casesDrawn = [0, 1, 2];
So you actually create a new array and attach a new click listener. What you actually seem to want is to create a global variable caseDrawn and a global randSelect function:
var casesDrawn = [0, 1, 2];
function randSelect() { /*...*/ }
// Attach keyup listener
document.body.addEventListener( 'keyup', function (e) {
if ( e.keyCode == 13 && casesDrawn.length > 0) {
randSelect();
}
});
// Attach button listener
document.querySelector("button").addEventListener("click", randSelect);
then randSelect() gets called on keypress and button click.

Categories