ToggleClass is not being applied to every single div

I am currently designing a pricing table with hover effects. You can view the progress here:

Upon hovering on a pricing table, all the divs are toggling classes which is not the desired behavior. I want each element to have its own separate interaction.

Here is the jQuery code I have implemented:

$('.package').hover(function(){
     $('.name').toggleClass('name-hover')
     $('.price-container').toggleClass('price-hover')
     $('.price').toggleClass('white-hover')
     $('.month').toggleClass('white-hover')
 });

The CSS adjustments are just to modify the current colors:

    .package .price-hover {
        background: #008ed6;
    }

    .package .white-hover {
        color: #fff;
    }

I have attempted using $(this), but it does not produce the desired effect.

Answer №1

$('.product').on('mouseover', function(){
    $(this).find('.title').toggleClass('title-highlighted')
    $(this).find('.cost-container').toggleClass('cost-hover')
    $(this).find('.cost').toggleClass('highlighted')
    $(this).find('.monthly').toggleClass('highlighted')
});

Answer №2

There is no need to complicate things by adding JavaScript when this can be easily accomplished with CSS alone.

.product:hover .price-container{
    background: #008ed6;
}

Answer №3

If you want to iterate through each element using jQuery, you can utilize the `each()` function:


$('package').each(function() {
  var currentElement = this;
  $(this).hover(function() {
    $(currentElement).find('.name').toggleClass('name-hover');
    $(currentElement).find('.price-container').toggleClass('price-hover');
    $(currentElement).find('.price').toggleClass('white-hover');
    $(currentElement).find('.month').toggleClass('white-hover');
  });
})

Answer №4

  • To ensure that only the classes for elements within the currently hovered over .package are changed, make use of the find function. Otherwise, classes will be modified for all related elements.
  • Additionally, the hover event consists of 2 functions: one is triggered when the mouse enters the hover area, and the other activates when the cursor exits the hover area. As per how you're managing the hover event, it toggles the classes twice - once on hover in and once on hover out, ultimately restoring it to its original state.

Experiment with this code:

$('.package').hover(function(){
     $(this).find('.name').addClass('name-hover');
     $(this).find('.price-container').addClass('price-hover');
     $(this).find('.price').addClass('white-hover');
     $(this).find('.month').addClass('white-hover');
 }, function(){
     $(this).find('.name').removeClass('name-hover');
     $(this).find('.price-container').removeClass('price-hover');
     $(this).find('.price').removeClass('white-hover');
     $(this).find('.month').removeClass('white-hover');
 });

Answer №5

$(".package").on("mouseover", function() {
    let $this = $(this);
    $this.find(".name").toggleClass("name-hovering");
    $this.find(".price-container").toggleClass("price-hovering");
    $this.find(".price,.month").toggleClass("white-onhover");
});

@Spartak Lalaj According to the jQuery documentation, starting from version 1.4, the .hover() method can have just one parameter. For more information, visit https://api.jquery.com/hover/

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

Tips on resolving the Warning message: "The event handler property `onExited` is a known property in StatusSnackbar component, but it will

When using the StatusSnackbar component, I encountered a warning about a known event handler property onExited. How can I resolve this issue? Component: import Snackbar from '@material-ui/core/Snackbar' import { withStyles } from '@material ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Embed video with a custom thumbnail in an iframe

Hello everyone! I'm a first-time user on stackoverflow seeking some help. Currently, I am using Dreamweaver to work with HTML and CSS in order to build a website. My task involves sourcing a video from a television archive and embedding it onto my si ...

Looking to deactivate a particular checkbox in a chosen mode while expanding the tree branches

I encountered an issue with a checkbox tree view where I needed to disable the first two checkboxes in selected mode. While I was able to achieve this using the checked and readonly properties, I found that I could still uncheck the checkboxes, which is no ...

How can Selenium in Python be used to click a JavaScript button?

I need help automating the click of a button on a webpage using selenium Here is the HTML for the button: <div class="wdpv_vote_up "> <input value="7787" type="hidden"> <input class="wdpv_blog_id" value="1" type="hidden"> </div& ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

Use jQuery to assign a value of "true" when a checkbox is

Can you guide me on how to use jQuery to implement a click function that sets the status value to 'true' if a checkbox is checked, and 'false' if it's not checked? If Checkbox 1 is checked, Status 1 should be set to true. Similarl ...

Ajax is incapable of achieving success or encountering failure

I'm having some trouble displaying search results on the view using AJAX. The action retrieves JSON data and sends it, but for some reason the AJAX call is not receiving the data. $(function () { $("#btnSearchForUser").click(function () { ...

How to position div elements side by side using CSS and center them, even on IE8

UPDATE: I have discovered that implementing Bart's solution is the correct one. With a 264px wide div containing the other divs and their 1px borders, I achieved the desired effect. I have updated my code to include his answer. Thank you, Bart. Once ...

Switch the Header Image on a Page in WordPress

I am currently using the Sunrise Theme from s5themes.com and I have a question regarding the header image on individual pages. It seems that all pages are displaying the same header image as the homepage, which is not what I want. Attached below is a scre ...

Steps for automatically retrying a failed expect statement in Jest

In my React application, I am utilizing Jest for performing unit testing. One aspect of my application involves a Material UI date picker with next and previous buttons. The selected date is displayed in the browser URL. Each time the user clicks on the ne ...

Using Node/Express to split the request headers with the .split() method

I am currently working on a way to determine if a specific item exists in the req.headers in order to make a decision on what to send back to the user. Here is my code snippet: function serveAppData(req, res) { console.log("CHECKME", req.headers); //var h ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

jQuery does not function properly when used with string variables

Why am I experiencing different results in Google Chrome when using a hard-coded string versus storing the same string in a variable? While the hard-coded string works properly, the same string stored in a variable does not produce the expected outcome. ...

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 ...

When a new VueJS project is created, it failed to automatically install the necessary basic HTML files and folders

Hey there, I am completely new to Vue.js. Just recently, I installed the Vue.js/CLI and created a brand new project using vue create test. This prompted me to choose from three options: > Default ([Vue 2] babel, eslint) Default (Vue 3 Preview) ([Vue 3 ...

Create an illustration of a canvas interacting with a database image source, but failing to display local images

When attempting to load an image onto a canvas, I encountered an issue. My code works without any errors when I use image.src="https://somelink", but throws a GET error when I try to import with image.src="../public/vercel.svg. Below is my c ...

Converting a curl command to a $.ajax() call in JavaScript: A step-by-step guide

I'm attempting to retrieve data from the Zomato API by using jquery ajax, however, they have provided a curl command instead. curl -X GET --header "Accept: application/json" --header "user-key: key" "https://developers.zomato.com/api/v2.1/cities" Is ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...