How to toggle two classes simultaneously using JQuery

Check out this code snippet: http://jsfiddle.net/celiostat/NCPv9/

Utilizing the 2 jQuery plugin allows for the following changes to be made: - The background color of the div can be set to gray. - The text color can be changed to red.

The issue arises when trying to change the color of the text by precisely pointing the mouse on it. I am looking to change both the background color of the div and the text color by simply clicking anywhere within the div.

I have attempted different combinations from various posts, but none have been successful.

(In an ideal scenario, I would also like to change the picture simultaneously!)

$(".item_unselected").on("click", function() {
$(this).toggleClass("gray_cliked_box");
$(".item_unselected").not(this).removeClass("gray_cliked_box");
});

$(".item_text_in_menubar").on("click", function() {
$(this).toggleClass("blue_cliked_text");
$(".item_text_in_menubar").not(this).removeClass("blue_cliked_text");

});

Answer №1

Although you are getting close, the reason you need to click on the text is because you are only applying the class to the text once it has been clicked, rather than when the div is clicked. Fortunately, you can streamline and correct your code by consolidating the event handling. When you click on the div, both items are set simultaneously.

You can achieve this by utilizing the find method in jQuery to locate the span that should be modified upon clicking the div. The revised JavaScript code is as follows:

$(".item_unselected").on("click", function () {
    $(".item_unselected").removeClass("gray_cliked_box");
    $(".item_text_in_menubar").removeClass("blue_cliked_text");
    var $this = $(this);
    $this.addClass("gray_cliked_box");
    $this.find(".item_text_in_menubar").addClass("blue_cliked_text"); 
});

Updated Fiddle: http://jsfiddle.net/NCPv9/3/

Essentially, this code removes the class from all elements and then adds the classes back to the desired ones. Moreover, you can use addClass directly instead of toggleClass since you know you are adding the class.

Answer №2

The issue at hand is related to CSS rather than jquery. I have made modifications to your CSS selector as follows:

.gray_cliked_box .item_text_in_menubar {  /*for jquery*/
    color: red;
}

As a result, the text will turn red when clicked.

The new selector specifies that any children of .gray_clicked_box with the class .item_text_in_menubar should have a color of red. This takes precedence over other styling rules for .item_text_in_menubar since it is a more specific selector.

http://jsfiddle.net/NCPv9/4/

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

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

What is the best way to incorporate random colors from a preselected color palette within my JavaScript code?

I couldn't figure it out var colorsList = ['#800000', '#A36386', '#FFD4D8, '#223CFF', '#F5FF5A', '#FF5555', '#A7EBFF']; var color = colorsList[Math.floor(Math.random() * colorsList. ...

Implementing a splash screen upon selecting the second exit option

Check out the code snippet here: https://jsfiddle.net/wust7gdy/ Once the curtain is raised, the exit button will appear. How can I introduce a splash screen after clicking the 2nd exit button? Currently, there is a splash screen that appears after click ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

Utilizing HTML snippets for AJAX integration

Let's dive in, I may be completely off track here. I am currently working with Wordpress. On a page I am creating an HTML select menu (Main Menu) with options that correspond to each page on the site. This menu is visible on the page. In addition, ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

The drawback of using a datepicker within an Angular input field

When attempting to open the Angular Material datepicker, it was appearing above the input field. How can I make it open below the input field instead? <mat-form-field appearance="outline" class="w-100 date-class"> < ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...

Starting with HTML5 can be a bit overwhelming, especially when it comes to compatibility with older systems

I am intrigued by the vast array of new possibilities available, but I find myself lacking in knowledge when it comes to Html5. One way to minimize the usage of IE6 and propel us into a more advanced era is to fully embrace new technologies like HTML5. Ho ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

`Creating a functional list.js filter``

I'm having trouble making the List.js filter function work properly. The documentation for List.js is not very helpful for someone new to development. Below is the code I am using: HTML: <div class="col-sm-12" id="lessons"> <input class= ...

Dynamic binding of CSS properties in AngularJS is a powerful feature that enables

I am attempting to dynamically bind the css property counter-reset in AngularJS. To see my efforts, check out this Fiddle link. Essentially, I aim to have the numbering of li elements begin with the number specified in the controller. Despite trying to us ...

Creating JSX elements in React by mapping over an object's properties

I need to display the properties of an object named tour in JSX elements using React without repeating code. Each property should be shown within a div, with the property name as a label and its value next to it. Although I attempted to iterate over the o ...

Using the splice() method to remove an item from an array may cause unexpected results in React applications

Dynamic input fields are being created based on the number of objects in the state array. Each field is accompanied by a button to remove it, but there seems to be unexpected behavior when the button is clicked. A visual demonstration is provided below: ...

Creating a dynamic dropdown menu using jQuery animation

I am looking to add animation to my top navigation bar. Currently, the dropdown menus just appear suddenly when hovering over the links in the top nav. Development site: I have attempted the following: <script> jQuery(document).ready(function() { ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

CSS: The button appears to be slightly lower than the label

For more information, check out this GitHub link Here is the HTML code snippet: <div class="col-md-12"> <div class="col-md-2"> Processing </div> <div class="col-md-4"> <button class="btn btn-primary">Hello</ ...

Notify the user with a Jqgrid alert when they attempt to select multiple checkboxes

When editing rows, I wanted to avoid multiple selections. In order to achieve this, I need to check the condition if(count>1) and display an alert message. I am struggling to figure out how to retrieve the count of selected checkboxes in jqGrid. var m ...

When Components in Vue are called in a Single File, certain elements may not be displaying as expected

I have just finished creating my components using Vue 2, Vuetify, and Vue cli - 4.5.15. I attempted to combine them into a Single Vue file but encountered issues with the components not displaying <v-icons>, <v-textfield>, and some other elemen ...

Steps to easily modify the color of Font Awesome stacked icons when hovering over them

I have incorporated two Font Awesome icons into my design: fa-circle-thin fa-user-plus These icons are stacked to create a circular icon appearance. <span class="fa-stack fa-sm"> <i class="fa fa-circle-thin fa-stack-2x"></i> <i c ...