Trigger click functions sequentially to display elements after specific actions are taken

Is there a way to make jQuery listen for clicks only at specific times? It seems that when I add event listeners, like $("#box").click(function(){, they are executing before the code above them finishes running.

Let's say I have two boxes that should respond to clicks in sequence - with the second box only becoming clickable after the first one has been clicked. Once clicked, both boxes should stop listening for further clicks. For example, box1 should turn red first, followed by box2.

I've tried searching for solutions without much success. I also experimented with adding if statements, but then the second box never triggers. Any assistance on this matter would be highly appreciated.

pass = 0;

function change() {
  console.log("enter change");
  $("#box").click(function() {
    $(this).css("background-color", "red");
    pass = 1;
  })

  if (pass > 0) {
    $("#box2").click(function() {
      $(this).css("background-color", "red");
    })
  }
}
div {
  height: 100px;
  width: 100px;
  background-color: black;
  display: inline-block;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div id="box"></div>
<div id="box2"></div>
<button onclick="change()"> change</button>

Answer №1

To optimize the functionality of this code, I recommend implementing a different approach. Continuously attaching click handlers at varying times can lead to confusion and unnecessary complexity in the code.

A more streamlined and efficient solution would be to bind all event handlers during the page load and then conditionally check within each handler if the page is in a state where the event should execute its logic.

Essentially, you can assign a class on click of #box and only allow the class to be added on #box2 once it has been applied to #box. Try the following:

$('#box').one('click', function() {
  $(this).addClass('foo');
});

$('#box2').click(function() {
  if ($('#box').hasClass('foo')) {
    $(this).addClass('foo').off('click');    
  }
});
div {
  height: 100px;
  width: 100px;
  background-color: black;
  display: inline-block;
  margin: 10px;
}
div.foo {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box"></div>
<div id="box2"></div>

There are several key points to consider here. For starters, jQuery 1.4.2 is outdated by almost 9 years. It's crucial to update to at least version 1.12.4 for legacy browser support or opt for the latest version in the 3.x branch.

Furthermore, avoid using inline event handlers like onclick and instead utilize unobtrusive event handlers. With jQuery already in use, employing the click() method is straightforward.

This implementation also includes one() to add an event handler that triggers just once, along with off() to remove the click handler after its initial execution.

Additionally, opting for addClass() over css() is recommended as it keeps CSS logic separate from JavaScript, promoting cleaner code.

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

Enhancing a specific area of an image using jQuery's zoom functionality

Currently, I am facing an issue with the clarity of my scanned document which is saved as a gray scale image at 150 dpi in TIFF format. The problem arises when I try to display this image online for form and identity verification purposes, as the small f ...

Ensure that only valid numbers can be inputted into an HTML number type field

My input number is as follows: <input type="number" id="quantity" name="quantity" (change)="firstRangePointChanged($event)" > I need to ensure that users cannot input invalid values like --99 (--) instead of ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

What is the best way to access a ViewChild element in the parent component without rendering it?

I am currently utilizing a component within another component in the following manner: <inline-help> <help-title>{{::'lang.whatIsThis'|i18n}}</help-title> <help-body i18n="lang.helpBody">& ...

What is the best approach to have a method in the parent class identify the type based on a method in the child class using TypeScript?

I'm faced with a code snippet that looks like this. class Base{ private getData(): Data | undefined{ return undefined } public get output(): Data | undefined { return { data: this.getData() } } } class ...

Displaying numerous images/items in a Bootstrap 2.3 carousel

I have been working on a PHP-based website that utilizes Twitter Bootstrap 2.0. Currently, I am retrieving user information from a MySQL database and attempting to display them in separate frames or items within a carousel instead of all at once using a wh ...

The jQuery placeholder plugin encounters an error stating 'jQuery is not defined'

Having an issue on this specific page where I keep encountering a 'jQuery is not defined' error in both Chrome and IE because of the jQuery placeholder script. The declaration of jQuery comes before the plugin script. Checked for any conflicts ...

Why won't hover over function properly in separate divs for two items?

My goal is to show text when hovering over a logo, but the text and logo are in different divs. Despite trying various solutions like using display: none and display: block, I still can't get it to work. import styles from '../styles/Float.module ...

Deleting Data with HTML Using the HTTP DELETE Method

I've encountered an issue with making HTTP DELETE requests in webapp2. Currently, I've resorted to using a different URI with GET method as a temporary workaround. However, I'd prefer to implement a more RESTful approach. Upon inspecting th ...

Display user account balances in real-time on the web browser by retrieving data from a secure private Ethereum

I am seeking to create a website that can display real-time updates of a user's wealth from a private Ethereum blockchain. Ongoing Issue (buggy) Currently, I have attempted to connect to a private Ethereum blockchain that is mining using a WebSocket ...

Submit additional data along with the form to the server

Is there a way to send both form data and additional values (such as {a:'A',b:'B',c:'C'}) to the server using jQuery ajax? The HTML code: <form id="myForm"> <p>firstname: <input name="firstname" type="text ...

Tips for invoking C language code from JavaScript by using the js-ctypes extension in Firefox

I need assistance with developing a Firefox extension that requires calling native C code. Here is my C program code: #include<windows.h> int add(int a, int b) { return(a + b); } And here is my JavaScript code: var {Cu} = require('chrome ...

Create a div element that initially aligns to the left, expands to the full width of the window, and then shrinks back

Hi there! I am currently diving into the world of javascript and jQuery, with a specific goal in mind. I want to create functionality where a div expands to the width of the window when clicked, then shrinks back down to its original size but switches alig ...

An error occurred when trying to set a cookie using Set-Cookie in a react application

Currently, I am immersed in a small project that involves user authentication via email and password before gaining access to their individual profiles. The backend operates on cookies which are established once the correct email and password combination i ...

I am in search of a method to rephrase the content while minimizing redundancy

I am looking to improve the code for handling two different conditions in the UI. Can someone suggest a better way to rewrite it? <i *ngIf="measures.length > 0"> <ul *ngFor="let m of measures"> <io-data-selection-row [text] ...

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

The functionality of the typeof operator is not behaving as anticipated

I am currently working on a script to verify the existence of a specific JavaScript object. var success = function(data) { var x= 0; var numOfCards = data.length; for (x=0;x<data.length - 1;x++) { if (typeof data[x].l ...

Retrieve a JavaScript object based on a specific value

Looking at my object : TeamMember = { 0 : {"ID": 100, "Name": "MNO", "Role": 2}, 1 : {"ID": 101, "Name": "PQR", "Role": 3}, 2 : {"ID": 103, "Name": "STU", "Role": 3} } I am trying to retrieve TeamMember[1] : {"ID": 101, "Name": "PQR", "Role": 3} a ...

Encountering issues with resolving dependencies in webdriverIO

I'm attempting to execute my WebdriverIo Specs using (npm run test-local) and encountering an error even though I have all the necessary dependencies listed in my package.json as shown below: [0-2] Error: Failed to create a session. Error forwardin ...

How can we prevent an unstyled list from causing text to drop to the next row?

As I am not an expert developer, I am in the process of creating a basic menu card using bootstrap. To keep it simple, I decided to use an unstyled list and added a span with float: right to ensure that the price is always aligned to the right. However, I ...