jquery persistently selects element even after altering the class

Having an issue with a button that needs to change its function after meeting a certain condition.

I am attempting to select the button by its class, remove that class when the condition is met, add a new class, and then perform another action. However, it is not working as expected.

Here is an example of my problem:

$('.button-1').click(function(){
    $('.box').width(function(){
        return $(this).width() + 10;
    });
    $(this).removeClass('button-1').addClass('button-2');
});
$('.button-2').click(function(){
    $('.box').width(function(){
        return $(this).width() - 10;
    });
    $(this).removeClass('button-2').addClass('button-1');
});

You can view the code on this Fiddle link.

My expectation was for the black box width to toggle between increasing and decreasing, but it continues to increase only.

Answer №1

To address this issue, you need to implement event delegation for dynamic binding. Here's an example of how to do it:

$(document).on('click','.button-1', function(){
    $('.box').width(function(){
        return $(this).width() + 10;
    });
    $(this).removeClass('button-1').addClass('button-2');
});
$(document).on('click','.button-2', function(){
    $('.box').width(function(){
        return $(this).width() - 10;
    });
    $(this).removeClass('button-2').addClass('button-1');
});

Check out the demonstration here.

Answer №2

Sure, that's one way to approach it...but have you considered using an additional variable to track if a click has occurred? This approach simplifies the code and allows for easy checking later on to see if the box has been enlarged.

By utilizing this method, you're also separating style from logic, which is generally seen as a best practice.

var clicked = false;
$('body').on('click', '.button', function(){

if (clicked) {
    $('.box').addClass('enlarged');
    clicked = false;
} else {
    $('.box').removeClass('enlarged');
    clicked = true;
}

});

Additionally, make sure to include a CSS class like the following:

.enlarged {
    width: 110px; 
}

I've also removed the button-1 and button-2 classes and instead applied the 'button' class directly to the 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

assigning a CSS class to an input element based on a certain condition

My dilemma involves an input field for which I need to conditionally apply a CSS class. For instance, if firstName == undefined, I want to apply the CSS class ng-dirty. To achieve this, I attempted: <input required [(ngModel)]="customer.firstName" nam ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

Creating flexible padding for child elements inside a container using CSS

I am facing a challenge in creating dynamic padding within a container. Consider the following HTML: <div class="sections-container"> <div class="section"> </div> <div class="section"> </div> </div> and the corres ...

Tips for displaying only the items that are currently visible in an AngularJS Dropdown

I am currently working with an AngularJs object that looks like this: $scope.data = {'options': [{ "id": 1, "text": "Option 1", "isHidden": 0 }, { "id": 2, "text": "Option 2", "isHidden": 1 }, { "id": 3, "text": "Option 3", "isHidden": 0 }]}; U ...

What could be the reason my form inputs are not capturing any data?

I am currently working with React to build a form, but I am facing an issue. Whenever I try to type in the form fields, nothing seems to happen. Upon inspecting the state of each input in the React dev tools, I noticed that it is only capturing one letter ...

Integrating a parameter into a plugin allows for displaying a specified number of elements in the output

A unique plugin is being used to create a vertical slideshow effect. This plugin scrolls the top-most div in a series of divs with the same class upwards, removes it from the container, and appends it to the bottom of the series within the container. The e ...

A guide on displaying complete text as the container width expands using Tailwind CSS and Next.js

On my platform, users have the ability to create albums and give them names of any length. When a user creates an album, it generates a div along with a link (the album's name) and two icons. I am looking to implement a feature where if a user enters ...

Utilizing Ajax to update the login form without reloading the page and displaying any errors

I have created a login form that utilizes ajax to handle login errors such as "incorrect password" from my login.php file. Instead of reloading a new page with the error message, it now displays the errors on the same login form, which is working perfectly ...

Issues arise when trying to render a component in React after importing the react-bootstrap library

After running npm init and installing react, react-dom, bootstrap, and react-bootstrap packages, I encountered an issue while trying to import components from the react-bootstrap library. The code import Button from 'react-bootstrap/Button'; resu ...

Cheerio in node.js encounters a problem while reading HTML files

I am brand new to JavaScript and I've hit a roadblock with Node Cheerio. Any assistance would be greatly appreciated. The code I'm currently working on can be found here: https://github.com/zafartahirov/bitstarter. Once the issue is resolved, t ...

The function call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

Using a JavaScript function to post the input value and then displaying it through PHP

I am striving to create an input field that will capture the value of what is typed and display it. The JavaScript function is designed to retrieve the value of the input box two seconds after the user stops typing and then post it. However, the issue lies ...

Unlocking the Potential of Larger jQuery Icons

In a recent announcement, the jQuery team unveiled new icons for their UI components. However, I have been unable to locate any examples of how to use them or where they can be downloaded from. Also, it appears that the themes in the ThemeRoller only provi ...

Error encountered while using JQuery Ajax to invoke server-side method in ASP C#

How can I call a server-side method using AJAX in an ASP C# application? I have the below code in my aspx file: function editApp(appID) { $.ajax({ type: "POST", url: "Default.aspx/GetSquare", contentTy ...

Querying two MongoDB collections simultaneously to locate a user based on their email address

I am working with two different collections, tutors and users, within my MongoDB database. Within the controller, I have a function called signin. In this function, I need to modify the condition so that it searches for a user in both the tutors and users ...

Divide the table row and store each cell using regular expressions

Here is the original source text: gi0/1 1G-Fiber -- -- -- -- Down -- -- Access gi0/2 1G-Fiber -- -- -- -- Down -- -- gi0/3 1G-Fiber -- -- -- -- Down -- -- gi0/4 1G-Fiber -- -- -- -- Down -- -- gi0/5 1G-Fiber -- -- -- -- Down -- -- gi0/0/1 1G-Fiber -- ...

Ways to evaluate and contrast two JSON values in JavaScript by their key names?

I am dealing with two JSON arrays that look like this: array1=[{a:1,b:2,c:3,d:4}] & array2=[{a:2,b:5,c:3,d:4}] Is there a way to determine which key in array2 has the same value as one of the keys in array1? For example, in array 1, key b has a value ...

Conclude the execution of promises after a for loop

I'm looking to enhance my code by ensuring that it waits for the asynchronous query called prom to finish before resetting the array and restarting the first for loop. This way, the array will be cleared before the loop begins again. items = []; var ...

Is it feasible to swap out the cursor for a personalized image of my choice?

Can I replace the cursor icon with my own custom image that I created in Photoshop? I have seen websites with custom cursor images, so I know it is possible. But how do I do it and is it a standard approach? Will it work across all browsers? ...

Using a percentage in CSS translate can result in an image appearing blurry

I am facing a frustrating issue. Whenever I align an image using percentage-based transform translate, it results in a slight blur. This problem is specifically related to percentage alignment. Here is the CSS snippet: img { display: block; height: ...