Element disappearing before it is supposed to - javascript

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>

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;
}

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

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++;
}

Resetting "this.id" within a nested if statement

I have this function to control a memory game.
The user is presented by a serious of images, after some seconds the images disappear and then the user has to click on the images in a pre-decided order.
For instance the user first need to click on the image that represents a football, then a tree etc. If the user fails at anytime the game is over.
The problem now is that I can't reach the second nested if-statement. This.id is stuck to the first image clicked, is there a way to reset this.id so that the user can click a second image? Or other solutions?
function flagsAddEventlistener() {
if (this.id == correctOrderArray[0]) {
points += 1;
userMessageElement.innerHTML = "Correct answer";
this.src = `flags/${correctOrderArray[0]}.png`;
if (this.id == correctOrderArray[1]) {
points += 1;
userMessageElement.innerHTML = "Correct answer";
this.src = `flags/${correctOrderArray[1]}.png`;
}
} else {
userMessageElement.innerHTML = "Faulty answer";
}
}
Since you need to know how many times a user clicked on the image, you need to add a state (a variable defined outside your listener).
Here is a simple example:
let counter = 0;
function flagsAddEventlistener() {
if (this.id == correctOrderArray[counter]) {
points++;
userMessageElement.innerHTML = "Correct answer";
this.src = `flags/${correctOrderArray[counter]}.png`;
} else {
userMessageElement.innerHTML = "Faulty answer";
}
counter++;
}

Javascript won't trigger not if nor else

I have JavaScript code that must move a div up and down. When I click it I want it to go up, then when I click the second time I want it to go down. My code is this:
function why()
{
if (document.getElementById("newton").style.bottom == 23) {
alert("I entered the IF");
document.getElementById("newton").style.bottom = 0;
}
else {
alert("I entered the ELSE");
document.getElementById("newton").style.bottom = 23;
}
}
The strange thing is that the first time I click the div it goes up and tells me the ELSE part was executed, but after this, clicking it won't produce any effect, it wont go back down. Why is this?
You need to specify a unit, like % or px or whatever.
function why() {
if (document.getElementById("newton").style.bottom == '23px') {
alert("I entered the IF");
document.getElementById("newton").style.bottom = 0;
} else {
alert("I entered the ELSE");
document.getElementById("newton").style.bottom = '23px';
};
}
<button id="newton" onclick="why()">click</button>
But I would toggle a class instead and put this change in CSS.
function why(el) {
el.classList.toggle('up');
}
#newton {
bottom: 0;
}
#newton.up {
bottom: 23px;
}
<button id="newton" onclick="why(this)">click</button>
I found out that if other js functions are wrong, it can affect my whole code,even other functions. The code was right, but since another function was wrong that made my code not work...Thanks for the toogle the class advice, I will implement it ;)

Javascript: more functions on one click button.Click counter

I was trying to make more functions on one click button. I am trying to detect how much the user is clicking. If the user clicks onetime: do something, If the user clicks second time: do something. if the user clicks for the third time: do something. But my code is not working at all. can someone tell me what is going on?
var ButtonClickEen = document.getElementById("buttonEen");
var ButtonClickTwee = document.getElementById('buttonTwee');
var clicks = 0;
buttonC.onclick = function(event){
clicks += 1;
};
if (clicks === 1) {
/* 1st click, Do something */
} if (clicks === 2) {
/* 2nd click, Do something else */
};
You have many script errors, starting with selection of elements from DOM at beginning, but main error is your click event function, which has to look like this:
var buttonC = document.getElementById("buttonC");
var clicks = 0;
buttonC.onclick = function(event){
clicks += 1;
if (clicks == 1) {
alert('Click 1');
} else if (clicks == 2) {
alert('Click 2');
} else {
alert('Click 3 or more');
};
};

Categories