Unable to get click function to work with multiple div elements

Using four div elements, I have implemented a feature where clicking on the first div causes all other div elements to change opacity. This is working correctly. However, I would like the opacity of the first div to remain unchanged when moving to another div.

$(document).ready(function () {
    $(".category-item").click(function () {
        $(this).addClass("black");
        $(".category-item").addClass("blue");
    });
});

Thank you in advance.

Answer №1

Your HTML code is not valid - check it out:

<div class="category-item" >
    <div class="img-responsive center-block">   </div>      
</div>
<div class="category-item" >
    <div class="img-responsive center-block">   </div>          
</div>
<div class="category-item" >
    <div class="img-responsive center-block">   </div>      
</div>
<div class="category-item" >
    <div class="img-responsive center-block">   </div>  
</div>

Here is the corresponding JavaScript:

$(document).ready(function(){
    $(".category-item").click(function(){
        $(".category-item").addClass("blue");
        $(this).addClass("black").removeClass("blue");
    });


});

Check out the demo

Answer №2

check out the fiddle demo Give this a try:

$(document).ready(function(){
          $(".section").click(function(){
              $(".section.active").removeClass("active");
            $(this).addClass("active");
           $(".section").addClass("highlight");

          });
        });

Answer №3

Check out this live demo to see the code in action

$(document).ready(function(){
  $(".category-item").click(function(){
              $(".category-item").removeClass("blue");
              $(".category-item").removeClass("black");
   $(".category-item").addClass("blue");
                $(this).addClass("black");
  });
    

});

Answer №4

Check out this Fiddle demo and give the code a try!

$(document).ready(function(){
          $(".item").click(function(){
              $(".item").removeClass("active");
              $(".item").removeClass("inactive");
              $(".item").addClass("active");
              $(this).addClass("inactive");
          });
        });

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

Unable to compile relative path of threejs using browserify and babel

As a newcomer to babel and browserify, I encountered an issue while trying to transpile with browserify and babel. After installing the threejs package and adding the following import: import * as THREE from 'three' Everything worked fine when t ...

Challenge with uploading Minio presigned URLs

I am encountering a problem with the Minio presigned URL. While I have successfully obtained the URL and used the PUT method to insert my file into my Minio bucket, I am unable to open certain file types such as jpg, png, or pdf. This is due to Minio autom ...

"Enhancing user experience with React.js and Socket.io: dynamically updating list item positions based on

export default class ReactApp extends React.Component { constructor(props) { super(props) this.state = { status: [], services: [] } fetchData((err,opt, data) => { function Exists(l ...

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

Testing React Component State Updates

I've been dedicated to achieving close to 100% unit test coverage with my React application, focusing particularly on the useAsync hook. I came across a code snippet from react hooks: import { useState, useEffect, useCallback } from 'react'; ...

What is the best way to ensure that my transitionend event is triggered?

I'm currently exploring the <progress> element and attempting to incorporate a CSS transition to achieve a smooth progress bar effect as its value increases. Despite my efforts, I can't seem to trigger JS after the transitionend event occur ...

What is the best way to incorporate the skrollr-body tag without altering the overall height of the

Skrollr has been a game-changer, so thank you to the geniuses behind it. I made sure to properly place the skrollr-body tag around all elements except for the fixed background in order to make it work on mobile. However, I'm noticing that it is cutti ...

The arrangement of imports in NodeJS can lead to unexpected errors

Having an issue with the order in which I include different models in my main server.js file using NodeJS. Below is the code from my product.js Product model file: var mongoose = require("mongoose"); var Dealer = require("./dealer.js") var productSc ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

VueJS: using dynamic class names within the style attribute

Within my VueJS application, I have implemented Materializecss modals within single page components. Each modal requires a unique dynamic ID due to the application's requirements. The code snippet below showcases this: <template> <div :i ...

Having difficulty passing a variable between two different PHP files

When attempting to modify data in the database for a specific user column, I encountered an issue. The code that I created only alters the data for the last user in the database, rather than the current user. For instance: Let's say I am logged in as ...

Will a JavaScript source map file continue to function properly even after the source code file has been minified?

My experience I specialize in utilizing TypeScript and Visual Studio to transform highly organized code into functional JavaScript. My skills involve configuring the project and Visual Studio to perform various tasks: Merging multiple compiled JavaScrip ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

jQuery now enables the number field to accept not only one period but multiple periods

I need to update a number field in a form to accept multiple periods, specifically for entering software version numbers. Currently, the code I am using only allows for one period to be entered, resulting in an error when two periods are added to the fie ...

Tips for Creating an Animated Progress Bar in a Slider

After implementing jQuery, I managed to create a unique slider on my website. This slider included a thumbnail with captions for each photo. Positioned below the thumbnail was a progress bar fixed in the center between the caption and the image. Users can ...

What steps should I take to address the issue of sanitizing a potentially harmful URL value that contains a

I've encountered a URL sanitization error in Angular and despite researching various solutions, I have been unable to implement any of them successfully in my specific case. Hence, I am reaching out for assistance. Below is the function causing the i ...

How to modify a nested object in MongoDB based on the JSON data provided

In my possession, there exists a structured form of JSON data as displayed below: [ {"size":100,"year":2015,"geography":"London","age":"21","gender":"Female"}, {"size":80,"year":2015,"geography":"Cardiff","age":"38","gender":"Male"}, {"size":80,"year":201 ...

Tips for aligning a dropdown button with the other elements in your navbar

I followed the code outline from a tutorial on We3schools, but I'm having an issue with the button not aligning correctly with the navbar. https://i.sstatic.net/fSRIT.png I attempted to adjust the code for proper alignment before publishing, but was ...

Does SameSite=Lax grant permission for GET requests from third-party sources?

After exploring the MDN documentation on SameSite=Lax, I have come to understand the following: In modern browsers, cookies can be sent along with GET requests initiated by a third-party website or during top-level navigations. This is the default behav ...