Hover over the first element to remove its class and replace it with a different element

I am attempting to develop a function that adds the class = "actived" to the first Element.

This class has a CSS style that highlights the element in question.

I have a list of 4 lines and I want the first one to automatically receive this class, while the other 3 receive it when hovered over.

Simultaneously, remove the class from the first element as soon as the mouse is removed. When the mouse is away, the first element should revert back to receiving the class = "actived" by default.

In this image, the first element with class = "actived" is displayed by default This image demonstrates how hovering over other lists removes the class from the first element

$(".news-list li").hover(
    function () { $(this).addClass('actived') },
    function () {
        $(this).removeClass('actived')
        if ($(this).hasClass == "") {
            $(".news-list li").first().removeClass('actived')
        }
    },
)
ul.news-list {
    max-width: 595px;
    margin: 0 auto;
}

/* All elements within li centered */
.news-list li {
    height: 47px;
    display: flex;
    align-items: center;
    font-size: 13px;
    font-weight: 600;
    border-bottom: 1px solid #38353a;
    transition: none;
    position: relative;
    z-index: 2;
}

/* On hover, show */
.news-list li.actived::before{
    border: 1px solid #38353b;
    background-color: #27242b;
    width: 630px;
    height: 50px;
    position: absolute;
    bottom: -1px;
    left: -17px;
    z-index: -1;
    -webkit-box-shadow: 0px 20px 20px -19px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px 20px 20px -19px rgba(0,0,0,0.75);
    box-shadow: 0px 20px 20px -19px rgba(0,0,0,0.75);
    content: '';
}

/* Clickable news title */
.news-list li a {
    color: #fff;
}

/* Position read more button */
.news-list li .wrap-btn {
    display: flex;
    flex-grow: 3;
    justify-content: flex-end;
    visibility: hidden;
}

/* Show red button on hover */
.news-list li:hover .wrap-btn {
    visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="news-list">
    <li class="actived">
        <a href="#">Join our WhatsApp group</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
    <li>
        <a href="#">Don't miss out, castle siege every Sunday</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
    <li>
        <a href="#">Father's Day promotion, take advantage now</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
    <li>
        <a href="#">Sapien gravida conubia orci varius faucibus</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
</ul>

Answer №1

You have the ability to achieve this effect without utilizing JavaScript by incorporating :hover in your CSS Selectors

ul.news-list {
    max-width: 595px;
    margin: 0 auto;
}
/* All elements inside li are centered */
.news-list li {
    height: 47px;
    display: flex;
    align-items: center;
    font-size: 13px;
    font-weight: 600;
    border-bottom: 1px solid #38353a;
    transition: none;
    position: relative;
    z-index: 2;
}

/* Show on hover */
.news-list:hover li:hover::before,
.news-list:hover li.actived:hover::before,
.news-list li.actived::before{
    border: 1px solid #38353b;
    background-color: #27242b;
    width: 630px;
    height: 50px;
    position: absolute;
    display: block;
    bottom: -1px;
    left: -17px;
    z-index: -1;
    -webkit-box-shadow: 0px 20px 20px -19px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px 20px 20px -19px rgba(0,0,0,0.75);
    box-shadow: 0px 20px 20px -19px rgba(0,0,0,0.75);
    content: '';
}

.news-list:hover li.actived::before {
  display:none;
}


/* Linkable title of the news*/
.news-list li a {
    color: #fff;
}
/* Positioning read more button */
.news-list li .wrap-btn {
    display: flex;
    flex-grow: 3;
    justify-content: flex-end;
    visibility: hidden;
}
/* Show red button on hover */
.news-list li:hover .wrap-btn {
    visibility: visible;
}
<ul class="news-list">
    <li class="actived">
        <a href="#">Join our whatsapp group</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
    <li>
        <a href="#">Don't miss castle siege every Sunday</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
    <li>
        <a href="#">Father's day promotion, take advantage now</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
    <li>
        <a href="#">Sapien gravida conubia orci varius faucibus</a>&nbsp;-&nbsp;
        <span>00 / 00 / 00</span>
        <div class="wrap-btn">
            <a class="btn-red read-more" href="#">Read more</a>
        </div>
    </li>
</ul>

If you prefer a solution involving JavaScript

var selected = null;
$(".news-list li").hover(
  function() {
     selected = $('.news-list li.actived').removeClass('actived');
     $(this).addClass('actived');
  },
  function() {
      $(".news-list li").removeClass('actived');
      selected.addClass('actived');
  }
);

Answer №2

Your hover function doesn't need to be so complex.

If you want the last hovered element to remain active even after the mouse is no longer over it, you can simplify things by removing the second function from the hover handler for the `mouseout` event.

To keep the highlight on the last hovered element:

During the hover event: remove the `actived` class from all possible elements (no need to check which one first) and then add it to the currently hovered element

$(".news-list li").hover(
  function() {
    $(".news-list li").removeClass('actived');
    $(this).addClass('actived');
  }
)

To remove highlighting from any element when the mouse leaves:

Follow the same steps as above, but also include `$(".news-list li").removeClass('actived')` in the mouseout function to remove it from all elements:

$(".news-list li").hover(
  function() {
    $(".news-list li").removeClass('actived');
    $(this).addClass('actived');
  },
  function() {
    $(".news-list li").removeClass('actived');
  },
)

To reset the highlight to the first element when the mouse leaves:

Similar to before, but during mouseout, add the `actived` class back to the first element:

$(".news-list li").hover(
  function() {
    $(".news-list li").removeClass('actived');
    $(this).addClass('actived');
  },
  function() {
    $(".news-list li").removeClass('actived');
    $(".news-list li").first().addClass('actived');
  },
)

Here's a working example:

$(".news-list li").hover(
  function() {
    $(".news-list li").removeClass('actived');
    $(this).addClass('actived');
  },
  function() {
    $(".news-list li").removeClass('actived');
    $(".news-list li").first().addClass('actived');
  },
)
ul.news-list {
  max-width: 595px;
  margin: 0 auto;
}

/* Center all elements within the li */

.news-list li {
  height: 47px;
  display: flex;
  align-items: center;
  font-size: 13px;
  font-weight: 600;
  border-bottom: 1px solid #38353a;
  transition: none;
  position: relative;
  z-index: 2;
}


/* Show on hover */

.news-list li.actived::before {
  border: 1px solid #38353b;
  background-color: #27242b;
  width: 630px;
  height: 50px;
  position: absolute;
  bottom: -1px;
  left: -17px;
  z-index: -1;
  -webkit-box-shadow: 0px 20px 20px -19px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 0px 20px 20px -19px rgba(0, 0, 0, 0.75);
  box-shadow: 0px 20px 20px -19px rgba(0, 0, 0, 0.75);
  content: '';
}

.news-list li a {
  color: #fff;
}

.news-list li .wrap-btn {
  display: flex;
  flex-grow: 3;
  justify-content: flex-end;
  visibility: hidden;
}

/* Show button on hover */

.news-list li:hover .wrap-btn {
  visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="news-list">
  <li class="actived">
    <a href="#">Join our WhatsApp group</a>&nbsp;-&nbsp;
    <span>00 / 00 / 00</span>
    <div class="wrap-btn">
      <a class="btn-red read-more" href="#">Read more</a>
    </div>
  </li>
  <li>
    <a href="#">Castle siege every Sunday</a>&nbsp;-&nbsp;
    <span>00 / 00 / 00</span>
    <div class="wrap-btn">
      <a class="btn-red read-more" href="#">Read more</a>
    </div>
  </li>
  <li>
    <a href="#">Father's Day promotion, take advantage of it</a>&nbsp;-&nbsp;
    <span>00 / 00 / 00</span>
    <div class="wrap-btn">
      <a class="btn-red read-more" href="#">Read more</a>
    </div>
  </li>
  <li>
    <a href="#">Sapien gravida conubia orci varius faucibus</a>&nbsp;-&nbsp;
    <span>00 / 00 / 00</span>
    <div class="wrap-btn">
      <a class="btn-red read-more" href="#">Read more</a>
    </div>
  </li>
</ul>

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

IE z-index bug affecting Youtube videos

I've been experimenting with the YouTube API and I've included the following code snippet in http://jsfiddle.net/aaronk85/wapFR/. <div id="video-wrap2"></div> <div id="video-wrap"> <div id="play-video"></div> &l ...

Unable to click on element in Firefox browser

Encountering an issue with the following error message: Element is not clickable at point (791, 394). Other element would receive the click: Command duration or timeout: 66 milliseconds Any ideas on what's causing this? Using selenium web driver ve ...

Utilizing Typescript to implement an interface's properties

After declaring an interface as shown below interface Base { required: string; } I proceeded to implement the interface in a class like this class MyClass implements Base{ method(): void { console.log(this.required); } } However, I ...

Is there a way to accurately retrieve the width of an element within setInterval without any delay?

I'm currently experimenting with increasing a progress bar using the setInterval function. So far, it seems to be functioning properly. var progressBar = $('.progress-bar'); var count = 0; var interval = setInterval(function () { va ...

Having trouble getting Calendly Webhooks to function in a node.js environment with ngrok?

Hello everyone, this is my first time seeking help on Stack Overflow so please bear with me if there are any flaws in my question. I recently started using the Calendly Teams version and decided to implement the Webhooks feature on a Node.js web applicati ...

Can Antd's Typography.Paragraph be used as a multi-row Menu title?

I am having trouble getting multiple rows to work inside the Antd Submenu. When I select only one row, it works fine. However, when I try to select multiple rows, the ellipsis is not shown at all and the text remains in one row. <SubMenu ...

Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...

$injector encountered a problem resolving the required dependency

Currently, I am attempting to adopt the LIFT protocol (Locate, Identify, Flat, Try(Dry)) for organizing my Angular projects. However, I am encountering difficulties in handling dependencies from other files. Here is the factory I have: (function () { ...

Progress Bar Modules

I am currently working on creating a customizable animated progress bar that can be utilized as follows: <bar [type]="'health'" [percentage]="'80'"></bar> It is functional up to the point where I need to adjust different p ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

Uncomplicating Media Queries in Styled Components with the Power of React.js and Material-UI

My approach to handling media queries in Styled Components involves three distinct functions. One function handles min-width queries, another deals with max-width, and the third caters to both min-width and max-width scenarios. Let me walk you through eac ...

Keep a vigilant eye on the peak utilization of memory within the Node.js process

I am in search of a way to effectively monitor the maximum memory usage in a Node.js process, regardless of whether there are memory leaks or not. The processes in question include both real applications and synthetic tests. My expectation is that it sho ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Fade-In and Fade-Out CSS Effect with Background Images Displaying a Blank Last Image

I've been experimenting with applying a CSS-only background image transition to a div, but I encountered an issue where after cycling through three specified images, the background reverts back to the original black color. Even stranger, when I adjust ...

Strip inline styles from HTML content in django-tinymce

I am experiencing an issue with django-tinymce where it automatically adds inline styles when I save content. I would prefer to remove this behavior and only save the content in plain HTML. Can someone assist me with resolving this problem? ...

How to implement a cyclic item generation feature in React.js

My function is meant to draw multiple items in a cycle, but it is only drawing the first item when I attempt to draw 5. This is my function: export default function CinemaHole() { const items = []; for(let i = 0; i < 5; i++) { item ...

Incorporating a hyperlink within a list item for an image

Currently, I am attempting to create a clickable image within an unordered list. Although the paragraph is clickable, unfortunately, the image itself is not responding as expected. <ul> <a href="/movies/test/"><li> ...

Reset input value when adding or removing inputs dynamically

Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear butt ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking? I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal ...