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

Tips for generating various series using dx-Chartjs

Trying to visualize ratings based on their type is proving to be difficult as I can't seem to figure out how to group the series according to types. The available chart options are: $scope.chartOptions = { dataSource: data, c ...

Ways to retrieve a concealed DOM element from a background window

I have been struggling to display a button that is located in the background window using the jQuery code below, but unfortunately it's not functioning as expected. On my webpage, I have a hidden button that should only be visible when a user adds a ...

Exploring the world of JSON on the internet

Hello there! I'm currently working on a project similar to . However, I am facing difficulties when integrating my code with a discord bot. I am questioning whether it is possible to host JSON data online directly with the code snippet below: documen ...

Place the div at the bottom of the container with a flexible height determined by the content-wrapper

Can anyone help with a css problem I'm having? I am trying to create two columns, each containing dynamic content and images at the bottom of the column. Here is an example image for reference: https://i.sstatic.net/pvOef.png I want these image bloc ...

Tips for transferring a file to PocketBase using NodeJs

Currently, I am in the midst of a project that necessitates uploading numerous PDF files to a PocketBase collection. All the necessary files are saved on my computer and my goal is to upload them using nodejs along with the PocketBase JavaScript SDK. Howe ...

Accessing the current frame of a video in JavaScript or jQuery

Currently, I am experimenting with the HTML video tag to play a video. Instead of retrieving the "currentTime" of the video, I am interested in obtaining the current frame using either jQuery or JavaScript. Despite my efforts in calculating the frame rate ...

Incorporating Subtitles into Videos using NodeJS and the FFMpeg Fluent API

I'm having trouble adding subtitles (srt) to a video stream using Node JS and FFMpeg... Here's what I've tried: var command = ffmpeg(file.createReadStream()) .input("C:\\code.srt").videoCodec('copy') .videoCodec(& ...

Ways to toggle the visibility of a div with a click event?

I am working on a project where I have a list view of items. I want to implement a feature where when a user clicks on an item, a hidden div below it will appear with options like price, quantity, and other details. I am looking for guidance on how to achi ...

Papaparse and vfile not functioning properly - Output appears jumbled

I recently posted a question on Stack Overflow about parsing large CSV files, the issue can be found here. The problem involves reading a CSV file and converting it into a table format. I attempted to use the code provided in one of the responses, but unfo ...

How can I close the colorbox and open a new regular window when clicking a hyperlink?

Hey there, I'm currently facing an issue with closing a colorbox when clicking "Click here to return to our website" and opening a regular browser window instead. You can check out the problem on this page: On the left navigation bar at the bottom i ...

Addressing responsiveness problems with Bootstrap navigation bar

Seeking assistance with setting up the fundamental bootstrap grid system. Despite my efforts, I am unable to make it work. Could someone guide me in creating the basic structure for the Navbar above? Specifically, focusing on using columns and rows with p ...

What causes inline-blocks to malfunction after a non-breaking space is inserted?

Here is some HTML code: <p id='one'>Hello World how are you.&nbsp;<span>Entrepreneur</span></p> <p>Hello World how are you.&nbsp;<span>Entrepreneur</span></p> Below is some CSS styling: ...

Unleashing the hidden power of a website's jQuery function - the ultimate guide!

I am looking to modify the delayedAutoNext function found on the homepage of pitchfork.com which rotates the pitchfork.tv images. My goal is to adjust the setTimeout value to a new number. Is there a way to accomplish this using a bookmarklet or userscrip ...

Click the button to reset all selected options

<form method="post" action="asdasd" class="custom" id="search"> <select name="sel1" id="sel1"> <option value="all">all</option> <option value="val1">val1</option> <option value="val2" selected="selected"> ...

An error known as "cart-confirmation" has been encountered within the Snipcart platform

I am looking to integrate Snipcart checkout in my Next.js application. However, when I try to validate a payment, I encounter an error message: An error occurred in Snipcart: 'product-crawling-failed' --- Item 1 --- [Item ID] 8 [Item Unique ID] ...

Issue: 'node' is not being recognized when attempting to execute the file using the package.json script

Currently diving into the world of Node.js, I encountered an issue stating "node is not recognized as an internal or external command" whenever I attempt to start my project using either npm start or npm run start. Strangely enough, running node index.js ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

The jQuery framework is causing AJAX/API data to be duplicated in the

I've been encountering a common issue for which I can't seem to find a straightforward solution. My current challenge involves using an API to fetch JSON data through an AJAX call. Upon receiving the data, it appears twice in both the console an ...

Text located in the bottom right corner of the window with the use of JavaScript

Is there a way to replace text at the bottom right of the window, as opposed to the page, so that it remains fixed in the corner of the window? I'm looking to create a "share" link that is always visible. ...

How can I initiate an AJAX POST request over HTTPS?

Despite my efforts, I am consistently encountering a 404 error when attempting to make an Ajax POST request. The specific error message reads: "GET 404 (Not Found)." Could this issue be related to the site's use of https? Below is the code snippet t ...