Resetting "this.id" within a nested if statement - javascript

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

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

Jquery If Else Statement Issue

I have multiple buttons and when I click each one I want an element associated with that button to slide down and then when I click the same button the same element slides back up. The code below works but if I click one button it slides down then I click the second button nothing happens because it runs the else if part of the code. How would I fix this?
var moreOption = 1;
$(".more-button").click(function(){
var buttonNumber = $(this).attr('buttonNumber');
if (moreOption === 1) {
$("#more"+buttonNumber).slideDown();
moreOption = 2;
} else if (moreOption === 2) {
$("#more"+buttonNumber).slideUp();
moreOption = 1;
}
});
Just use a data-attribute on the button and switch the state manually like this:
<button class="more-button" data-showMore="1" data-buttonNumber="1"/>
$(".more-button").click(function(){
var buttonNumber = $(this).data('buttonNumber');
var moreOption = $(this).data('showMore');
if (moreOption == '1') {
$("#more"+buttonNumber).slideDown();
$(this).data('showMore', '2');
} else if (moreOption == '2') {
$("#more"+buttonNumber).slideUp();
$(this).data('showMore', '1');
}
});

Creating a higher order function to compare values

So my assignment is to create a memory card game. We are required to use jQuery or JavaScript to flip the cards, compare them, then un-flip them.
So far I can get up to two cards to flip, but I can't get them to un-flip or test for an icon match yet.
I think I need to use a higher order function, but I don't know exactly how to write it (especially because I'm really hung up on comparing values to test if the cards match or not).
Here's my jQuery stuff so far:
var track = 0;
$('li').click (function(){
track++
if (track === 1){
$(this).addClass('flipped')
$(this).children().css('opacity', '1');
console.log(track);
}
else if (track === 2){
$(this).addClass('flipped')
$(this).children().css('opacity', '1');
console.log(track)
}
});
$('li').click (function(){
if ($(this).val() == ($(cardFlip).val ()){
$(this).removeClass('flipped')
$(this).addClass('permanent');
}
else {
$(this).removeClass('flipped');
$(this).childre().css('opacity', '0');
}
});
I have corresponding CSS classes that are 'flipped', 'permanent', and ones for the card's starting point and the icon.
JS Fiddle
https://jsfiddle.net/9b2038zx/
You need only one click event to bind.
var track = 0;
var flippedExists = false;
var flipped;
$('li').click (function(){
track++
if (flippedExists){
if ($(this).val() == flipped.val()){ //success
$(this).removeClass('flipped')
$(this).addClass('permanent');
flipped.removeClass('flipped')
flipped.addClass('permanent');
}else { //fail
flipped.removeClass('flipped');
flipped.children().css('opacity', '0');
}
flippedExists = false;
}else{ //first flip
flippedExists = true;
flipped = $(this);
$(this).addClass('flipped')
$(this).children().css('opacity', '1');
}
});

Javascript - iterate to the next element based on condition

I'm stuck on how to iterate to the next element based on the condition in a function. Once the user highlights the right word and the message well done gets displayed, it should move on to the next definition/word taken from the array onA. At the bottom, I've put a pseudo code, as I don't know how to access the result of the conditional statement from the function.
var onA = [
{t: "grooming", d: "an activity when someone builds an emotional connection with a child to gain their trust for the purposes of sexual abuse or exploitation."},
{t: "cyberbullying", d: "an activity that involves the use of ICT, particularly mobile phones and the internet, deliberately to upset, threaten and intimidate someone else."}
];
function getSelectionHandler(index) {
return function clickHandler() {
var txt = '';
var feedback = document.querySelector("#onA .feedback");
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
// Display the selected text
document.querySelector("#onA .word").innerHTML = txt;
// Change the type of bootstrap alert depending on success
function feed(oldClass, newClass, message) {
feedback.classList.remove(oldClass);
feedback.classList.add(newClass);
feedback.innerHTML = message.bold();
}
// Check if the selected word is correct
if (txt === onA[index].t) {
feed("alert-warning", "alert-success", "Well done!");
} else {
feed("alert-success", "alert-warning", "Try again!");
}
};
}
var i = 0
while (i<onA.length) {
document.getElementById("onA").onclick = getSelectionHandler(i);
document.querySelector("#onA .def").innerHTML += onA[i].d;
if condition in the if statement above is true:
i++
}
Global variable can be used to record the current state. I just write it bear hand, you have to debug it if necessary.
function getSelectionHandler(){
var txt = '';
var feedback = document.querySelector("#onA .feedback");
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
// Display the selected text
document.querySelector("#onA .word").innerHTML = txt;
// Change the type of bootstrap alert depending on success
function feed(oldClass, newClass, message) {
feedback.classList.remove(oldClass);
feedback.classList.add(newClass);
feedback.innerHTML = message.bold();
}
// Check if the selected word is correct
if (txt === onA[index].t) {
feed("alert-warning", "alert-success", "Well done!");
index++; //increase before showing next or checking end
if (checkEnded()){
//all end, show end msg
feed("alert-warning", "alert-success", "Finish!");
}else {
//show next
showNext();
}
} else {
feed("alert-success", "alert-warning", "Try again!");
}
}
function checkEnded(){
return index >= onA.length;
}
function showNext(){
document.querySelector("#onA .def").innerHTML += onA[index].d; //display next item
}
var index = 0; //global index for selecting from the array
document.getElementById("onA").onclick = function(){getSelectionHandler();} //register hanlder onc time only
document.querySelector("#onA .def").innerHTML += onA[index].d; //display first item

Javascript How to trigger a function when we User Tries to Exit or Refresh the Page

When a user tries to exit the page after reading price of the product, i want to offer them 1st discount.
If they select 'YES' they buy the product instead of closing the window, if they select 'NO' then i would make 2nd discount
offer and this time it will be the last offer.
If they click 'NO' again even second time, his browser will
close or else he would buy the product at the given 2nd discount
price.
My Example is illustrated below:
<script type="text/javascript">
function getOffers()
{
var question1 = confirm("Wait! we are now offering this Product in $25.00, buy it?");
if(question1 == 'true')
{
alert('You have purchased this product for $25.00');
}
else
{
var question2 = confirm("Wait! we would like to make one Final Offer, price of Product in $15.00, buy it?");
if(question2 == true)
{
alert('You have purchased this product for $15.00');
}
else
{
//Close this window
}
}
}
</script>
My question is, how can i trigger this function when user tries to exit (or) refresh the page.
Additional INFO:
I have rewritten the code and trying to fix the annoying page load popup, can any one suggest me on this?
<script type="text/javascript">
function getOffers()
{
//alert(firrsTime);
if(firstTime == 'no')
{
var question1 = confirm("Wait! we are now offering this Product in $25.00, buy it?");
if(question1 == 'true')
{
alert('You have purchased this product for $25.00');
}
else
{
var question2 = confirm("Wait! we would like to make one Final Offer, price of Product in $15.00, buy it?");
if(question2 == true)
{
alert('You have purchased this product for $15.00');
}
else
{
//Close this window
}
}
}
}
window.onunload = function(){
firstTime = 'no';
getOffers();
}
window.onload = function(){
firstTime = 'yes';
getOffers();
}
</script>
I am trying to pass a global variable 'firstTime' to check if it is from onLoad then dont display offer if it is from onUnload then display offer. Is there any solution on this problem?
<body onunload="OnUnload()">
then
function OnUnload()
{
//put code here
}
Use the onunload and onload.
window.onunload = function(){getOffers();}
window.onload = function(){getOffers();}
Though it will show it when user first loads the page, so i wouldn't recommend on doing that.
About the way to distnguish between First load and refresh,
Have not tried this, but i found this code somewhere :
function OnCrmPageLoad()
{
//bind to the onsave event
crmForm.attachEvent(“onsave”,OnCrmPageSave);
if (crmForm.new_ispostback.DataValue == true)
{
//form was saved
//reset the field
crmForm.new_ispostback.DataValue = false;
}
}
function OnCrmPageSave()
{
// validate form if needed
crmForm.new_ispostback.DataValue = event.returnValue = true;
crmForm.new_ispostback.ForceSubmit = true;
return true;
}
Play around with it.

Categories