Fresh class retains the characteristics of the former class

As I navigate my way through learning jQuery, I've encountered a puzzling issue that I can't seem to solve.

No existing articles seem to address my specific problem, so I am turning to this platform in hopes of finding a solution.

I'm puzzled by the fact that my objects continue to exhibit the behavior of their previous class even after changing classes. Whenever I set up a hover action for a particular class and then change the class by clicking, jQuery still executes the animation for the old class.

I've tried using both toggleClass() and combining removeClass/addClass without success:

https://jsfiddle.net/biest9160/f0na6sro/

var wide = function() {
  $(this).animate({ 'width': '120px' }, 200);
}

var normal = function() {
  $(this).animate({ 'width': '100px' }, 200);
}

$(document).ready(function() {
  $('.class1').hover(wide, normal);

  $('.class1').click(function() {
    $(this).toggleClass('class1 class2');
  })
})
div {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  margin: auto;
}
.class2 {
  background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>

I can't quite grasp why the hover action continues to trigger even after the object has a different class applied to it.

Answer №1

At first, you link the event to the element using the specified class. Even after the class is modified, the event remains attached to the same element.

If you want to eliminate the event, you have the option to utilize .unbind. For removing the .hover event, refer to this response.

A practical demonstration implementing .unbind to eradicate the event and subsequently reattaching it appears in the code snippet below (essentially a toggle hover event):

var wide = function(){
    $(this).animate({'width':'120px'},200);
}

var normal = function(){
    $(this).animate({'width' : '100px'},200);
}

$(document).ready(function(){
    $('.class1').hover(wide,normal);
    
    $('.class1').click(function(event){
        var $this = $(this);
        $this.unbind('mouseenter mouseleave'); // remove hover
        if( $this.hasClass('class2'))
        {
            $this.hover(wide, normal); // reattach hover
        }
        $this.toggleClass('class1 class2');
    })
})
div{
    width:100px;
    height:100px;
    border: 1px solid #000;
    margin: auto;
}

.class2{
    background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>

Answer №2

To ensure event binding on parent elements, utilize the .on() method.

Illustrated below is an example:

$(document).on("click", '.class1', function(){
        $(this).toggleClass('class1 class2');
    });

This approach will undoubtedly be effective...

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

What is the correct way to utilize top-level "await" within TypeScript in Next.js?

One issue I encountered was when attempting to use "await" at the top-level like this: const LuckyDrawInstance=await new web3.eth.Contract(abi) A warning popped up in the terminal indicating to set experiments.topLevelAwait to true. However, even after t ...

Problem with Bootstrap container-fluid overlapping with floated element

I am struggling with the layout of my card body, which includes a floating logo and rows enclosed in a container-fluid. While everything looks great in Chrome, I am facing alignment issues in Edge and Firefox. I have considered using absolute positioning ...

transferring information from a nested input field in Vue to its parent component

I need to send the input data from a child component to the parent component's data property by using the $emit method. Directly binding the transmitted property to the child property using v-bind within the <input v-model="userinput" /&g ...

Steps to display a text box once the dropdown list is updated

I have a dropdown menu with two options <div class="form-group"> <span class="col-sm-4 control-span">Member Type</span> <div class="col-sm-8"> <select class="form-control" id="membertype" name="me ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

Is it possible to implement a single OrbitControls with two cameras in ThreeJS?

Is there a way to link the OrbitControls of two canvases on the same page? For example, if the user zooms in on one canvas, I want the other canvas to also zoom in simultaneously. How could I achieve this synchronization between multiple canvases? ...

Updating the table row by extracting data and populating it into a form

As part of my project, I am implementing a feature where I can input 'Actors' into a table using a Form. This functionality allows me to select a row in the table and retrieve the data of the chosen Actor back into the form for updating or deleti ...

What is the best way to extract basic information from a JSON object?

What is the best way to retrieve the weight value from this specific object? var prescription = "{'type':'" + $('#medi-type option:selected').val() +"',"+ "'weight':" + $('#weight').val() +","+ ...

Having difficulty aligning Divs perfectly?

I'm struggling to center four green divs that have a float left, surrounded by a wrapper div in blue. I want them to be aligned a certain way, but on larger screens, they are not displayed in the center. I need them to float underneath each other when ...

Are there any discussions underway about updating JSON standards to officially permit unquoted property names?

Technically speaking, the following JSON is considered invalid: { color: "blue", size: 14 } This is because according to the specification, property names like "color" and "size" should be enclosed in quotes, like this: { "color": "blue", "size" ...

Is there a way to use flexbox to decrease the size of images?

Struggling to make my code mobile-friendly. The PC version looks good, but on mobile, the bio stretches and text goes off the page. I can't seem to get the picture to shrink when viewed on a mobile device, or have the content neatly boxed alongside it ...

Go to a different webpage containing HTML and update the image source on that particular page

I am facing an issue with my html page which contains multiple links to another page. I need to dynamically change the image references on the landing page based on the link the user clicks. The challenge here is that the link is inside an iframe and trigg ...

Utilizing React and MaterialUI to create a dynamic GridLayout with paper elements

I am using the react-grid-layout library to create a dynamic grid where each item is a paper component from the React Material UI. However, I encountered an issue while running the application. The browser displayed the error message: "TypeError: react__W ...

How can JS be used to create content without refreshing the page?

On my website, I have a staff directory where each individual can be selected by clicking on their profile. When a staff member is clicked, a jQuery mobile popup opens and loads dynamic content using AJAX. Within this popup, users have the option to delete ...

Can we utilize conditions to both select and deselect items using JavaScript and PHP together?

I have a selection list with checkboxes that is dynamically generated based on certain conditions in the code snippet below. if ($data_inteiro_01 <= $data_inteiro_02) { if ($parcela[$i] === 0) { $display = 'disabled'; } } els ...

Why isn't the content of the initial tab in a <section> shown when clicking a link in the side-drawer?

View the JSFiddle here. Within this MCVC, a side drawer is implemented (opened by clicking the top left button) that contains three labeled links: Link One, Link Two, and Link Three. Each link has an href attribute value that starts with "#" concatenated ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: https ...

Save documents in Firebase storage

Currently in the process of developing a web application using Firebase and Angularjs as my frontend tools. Curious to know whether it's feasible to store various file types within the Firebase DB. Could you shed some light on any potential limitatio ...

Modify the parent's style in CSS based on the presence of certain specified children

I'm working with an HTML element that can contain a child with the ID 'slideshow' <div id='content'> <div id='slideshow'> </div> </div> Alternatively, it could have a different child like t ...

Specialized function to identify modifications in data attribute value

I have a container with a form inside, featuring a custom data attribute named data-av Here is how I am adding the container dynamically: > $("#desti_div").append("<div class='tmar"+count+"'><div > class='form-group col-md-6 ...