The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2.

Below is the code snippet in question:

$(function() {
  var turn = 2;

  if (turn == 1) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("x").animate({
        opacity: 1
      }, 1000);
    });
    turn = 2;
  } else if (turn == 2) {
    $(".box").on("click", function() {
      var $thisBox = $(this).children();
      $thisBox.addClass("o").animate({
        opacity: 1
      }, 1000);
    });
    turn = 1;
  } else {
    document.write("Uh Oh");
  }
});

I am perplexed by this recurring issue. Can anyone shed light on why this behavior persists?

Answer №1

To ensure proper functionality, it is important to set the onClick listener only once and then evaluate the value of the turn variable within the function triggered by the onClick event.

$(function() {
  var turn = 2;
  
  $(".box").on("click", function() {
    if (turn === 1) {
      console.log('foo');
      turn = 2;
    } else if (turn === 2) {
      console.log('bar');
      turn = 1;
    } else {
     console.log("Uh Oh");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'>Click me</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

react tried to recycle markup error

Working on server-side rendering with React, encountering an error mentioned below. Here is the context: I have 2 React components, each stored in its own separate folder: - react-components - component-1-folder - component-1 - component-2-fo ...

How can I retrieve a data field with a colon in its key using Cytoscape.js?

After diligently going through the official documentation and following the steps in the tutorial, I have successfully managed to access a node's data field and use it for labeling, as long as the key is a simple string. However, my data will contain ...

Utilizing static methods to interact with page elements

I am currently utilizing an ASP.NET datepicker and triggering a static event when a user selects a date using jQuery code like the following: <script> $(document).ready(function () { $("#datepicker").datepicker({ onSelect: f ...

Troubleshooting image alignment problem within a flexbox display

Is there a way to align the two images so that the bottom right of the first image meets the top left of the second image? I'm struggling to figure out a solution, especially considering different browser sizes. Any advice or suggestions? .flexbox ...

Utilizing jQuery grep() to sort through a JSON array

Despite my attempts to find a suitable example on this platform, I am still struggling to adapt them to my specific needs. Essentially, all I require is to filter some JSON results using the grep() function. Here is the JSON data that I am working with: ...

The utilization of useEffect causes the page to go blank

Essentially, the issue is that once I include useEffect(() => { const fetchData = async () => { const result = await fetch('http://localhost.com/ping'); console.log(result) }; fetchData(); }, []); in my compone ...

The data-ls attribute is currently not permitted on the svg element. Is there a way to fix this issue?

Upon running my site through the w3cvalidator tool, I encountered the following errors: "Attribute data-ls not allowed on svg element at this point" and "End tag svg did not match the name of the current open element (use)". Below is a snippet of the cod ...

Recently updated the versions of jquery/jquery-ui, and event.stopPropagation(); is no longer functioning as expected

Seeking assistance with an issue following a jQuery upgrade. After updating jQuery to version 3.3.1 and jQuery-ui to 1.12.1, along with jquery-migrate-3.0.1.min.js inclusion, code that previously functioned now produces an error for which I'm struggl ...

ERB failing to interpret Ruby script

Hello, my index.html.erb file looks like this: <h1>Bookmarks</h1> t <% @books.each do |b| %> <div class="book"> e <div class="row"> s <div class="col-md-1"> t <p class="rank-this ...

what can prevent a React component from re-rendering?

Being a novice in the realm of React, I find myself with a perplexing query. Within my application, I have two distinct components - the parent component named Goals and its child, EditGoal. The Goals component functions to display all goals, while the Edi ...

Passing data from a method callback to a function and returning a variable in the same function

Is there a way to properly return the latlon variable from the codeAddress function? The typical 'return latlon' doesn't seem to work, possibly due to scope issues. Any suggestions on how to resolve this? function codeAddress(addr) { ...

Having trouble understanding the odd behavior in IE7. Suddenly seeing a scrollbar appear when hovering

The webpage layout I am currently experiencing issues with can be found at the following link: When viewing this page in ie7 or ie8 Compatibility View mode, a strange horizontal scrollbar appears whenever I hover over one of the menu items. It seems that ...

Combining two JSON arrays into a single array using Node.js

Two JSON arrays are available: var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{sec:'A', class_name:'xyz' ...}] I am looking to combine these arrays into a single array. var finalObj = [{id:1, name: 'xxx' ...},{i ...

Configuring routes for Angular4 router is a vital step in creating a

Issue: I am currently setting up routes for my application, aiming to structure the URL as https://localhost:4200/hero=id, where the 'id' will be dynamically selected. However, this setup is not functioning as expected. If I attempt to use a URL ...

Change a Character or Word in JavaScript after it's been typed

If I were to type the word "hello" into a textarea, is there a way for me to select that specific word and modify it afterwards? For instance, let's say I typed hello without hitting the space bar; could the system recognize this word and automaticall ...

Experiencing issues with Jquery Ajax calls causing Internet Explorer to crash?

This is my first time posting on this website, so I apologize in advance if I make any mistakes with formatting. Currently, I am working on developing an MMO using Javascript and jQuery. Everything seems to be running smoothly in Chrome, Safari, Firefox, ...

Analyzing the differences in environment management between express and dotenv

Lately, I've noticed an abundance of tutorials and articles discussing NodeJS and the dotenv library. One common practice that keeps coming up is defining an ENV_MODE=development variable within the config.env file. However, it got me thinking - does ...

Creating a mesmerizing parallax effect for your image: A step-by-step guide

Looking for help to create a parallax effect on an image when hovered over. Does anyone have any advice or resources? Feeling frustrated at the moment. Here is an example link for reference: http://codecanyon.net/item/jquery-moving-perspective/full_scre ...

Audio issues plaguing audio playback on Discord

After spending two exhausting days, I am still trying to figure out what is going on. I am currently working on a Bot for my Discord Channel that should play an audio.mp3 file when a specific command, like !laugh, is entered. However, despite trying variou ...

What is preventing my counter from functioning when I click on the canvas?

I am attempting to increment the count every time a bouncing ball in the browser is clicked using this.setState({count: this.state.count + 1});. I thought my code was correct since I have done similar tasks before without using canvas, but it's not fu ...