Learn how to dynamically add a class to an element when hovering, and ensure that the class remains even after the mouse has

I'm facing difficulty with this task - when hovering over elements, an active class should be added to them. However, when moving the mouse to another section, the active class should remain on the last element hovered. Additionally, the first block should have the active class by default.

<div class="work-elem">
<div class="work-elem">
<div class="work-elem">
<div class="work-elem">

$(".work-elem:first").addClass("active");
    $(".work-elem").each(function() {
        $(".work-elem").hover(function() {
            $(this).removeClass("active");
            $(this).addClass("active");
        },
        function() {
            $(this).removeClass("active");
        });
    });

Answer №1

$(".work-elem").mouseover(function() {
  $(".work-elem").removeClass("active");
  $(this).addClass("active");

});
div {
  width: 20px;
}
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="work-elem active">1111</div>
<div class="work-elem">2222</div>
<div class="work-elem">3333</div>
<div class="work-elem">4444</div>

Answer №2

Opt for mouseenter & mouseleave over hover:

    $(".work-elem:first").addClass("active");
    $(".work-elem").each(function() {
        $(".work-elem").mouseenter(function() {
            $(this).removeClass("active");
            $(this).addClass("active");
        }).mouseleave(function(){
              $(this).removeClass("active");
        });
    });
.active{
   color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="work-elem">What about</span>

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

Enable the ability to scroll and click to navigate an overlapping Div element

A customer has a website with a dark teal design and is not pleased with the appearance of the scroll bar, as it disrupts the overall style. The client requested that I find a solution without using third-party libraries, and one that they can easily under ...

``From transitioning from Django templating to implementing a full RESTful architecture?

Looking to convert my django/html/css website to a REST (json) structure. Previously reliant on django template rendering for frontend responses. Interested in how to manage url redirection and incorporate json data into html templates without the use of ...

Top Tips for Generating an A - Z Index with Linq in Asp.net

I am looking to develop an A - Z index that can extract information from a SQL database using linq. I am exploring the best approach to create a user-friendly interface where users can easily navigate through the alphabet to find relevant information. Her ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...

The request is being redirected to an invalid destination, resulting in

I am facing an issue with a simple Jquery dialog box on my website. The dialog contains a button that sends the page to the server for processing. However, after some checking, the server redirects the page to another link. The problem arises when I use r ...

Designing php/mysql data in a container

After successfully converting an ordered list output into a div output, I now face the challenge of stacking arrays on top of each other (and side by side with the two divs) like they would in an ordered list. Here is the original code snippet: <?php ...

Tips for implementing server-side rendering in Jade using an Array of JSON objects instead of just a single JSON object

In my Node.js server, I am working with an array of JavaScript objects retrieved from a MySQL query. To pass this array to my Jade template, I use the following code in my router.js: data = JSON.stringify(rows[0]); res.render('yourUploads', {fro ...

Retrieving the 'red' pixel data from the texture rendered with gl.texImage2D

My objective is to transfer a Float32array to my fragment shader using a texture in order to process the data within the shader and then send it back to JavaScript. Since the data is not in the form of an image, I opted to transmit it as 'gl.R32F&apos ...

Attempting to display the todo item in the form of <li>, however, the todo.name property is not

I am currently developing a task manager application and have encountered a puzzling issue: When I include the Todo component within the TodoList component and pass the todo item as a prop todo = {name: "ssss", status: false, id: 0.0289828650088 ...

I desire to alter the description of an item within a separate div, specifically in a bootstrap

I used the map method to render all the images. However, I need a way to track the current image index so that I can change the item description located in another div. Alternatively, if you have any other solutions, please let me know. App.js : import Ca ...

Issue with AJAX call not functioning properly within PHP document

I've encountered an issue with a form that triggers an ajax call upon clicking the submit button. The ajax function is located within a PHP file as I need to populate some variables with data from the database. However, the before / success callbacks ...

Tips for implementing validation on dynamically inserted fields in a form

My form has two fields, and the submit button is disabled until those fields are filled with some text. However, if I add a third field dynamically using AngularJS, validation will not be supported for the new field. Check out the example here <butto ...

Mesh does not display texture in three.js

I've been attempting to add a texture to my sphere mesh using the code snippet below: var loader = new THREE.TextureLoader(); var balltex = loader.load("pic1.jpg"); var ballmat = new THREE.MeshBasicMaterial({ map: balltex }); var ballgeo = new THREE ...

The react-xml-parser package is asking for Babel version "^7.0.0-0", however it was instead loaded with version "6.26.3". I have already attempted all available solutions to resolve this issue

I have attempted numerous solutions from the Github community regarding this issue, but unfortunately none have worked for me. /node_modules/react-xml-parser/dist/bundle.js: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you ha ...

How can we utilize javascript to implement the jQuery "highlight" theme styles?

I have integrated jQuery UI Themes into one of my web applications. When applying button styling, I typically use the following jQuery code: $(".button").button(); In this case, .button represents the class associated with the button to be styled using ...

Tips for incorporating JavaScript into elements that have been modified using jQuery's .html() method

Consider this example: $('#key').on('click', function(){ $('.task').html("<button id='key'>Button</button>"+Date()); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.j ...

Adding a number repeatedly and showing the result

I have been searching for a solution to this particular problem for quite some time now, but unfortunately, I haven't been able to find one yet. It would be incredibly helpful if someone could guide me in the right direction. Let's say we start ...

The Vue v-on:click event listener seems to be unresponsive when applied to a

I've been attempting to utilize the on-click directive within a component, but for some reason, it doesn't seem to be functioning. Whenever I click on the component, nothing happens, even though I should see 'test clicked' in the consol ...

The issue of array sorting, specifically the function(a, b) {return b.value - a.value), is causing some

I am struggling to retrieve data from firebase and sort them according to the field 'overallScore' in descending order. Despite following suggestions like using array.sort(function(a, b) {return b.value - a.value), I have not been successful in s ...