What is the best way to make a div that fades away after a set period, but remains visible when hovered over?

I am currently working on implementing a notification system that will appear for a few seconds and then vanish. However, I want to give users the option to hover over it with their mouse to prevent it from disappearing. It would also be nice to have the notification disappear on click, although that is not mandatory. I am unsure of how to make the hover functionality in HTML interact with embedded Ruby to halt the timeout. It may require a restructuring of the code to achieve this. Below are snippets of relevant CSS, HTML, and ERB code (not executable):

setTimeout(function() {
  $('#alert_box').fadeOut('fast');
}, 3000);
.alert_wrap {
  padding: 0px 50px;
  margin-top: 3px;
  height: 5%;
  background-color: rgba(255, 0, 0, .3);
  border: 3px solid red;
  grid-row-start: 2;
  justify-self: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<% unless notice == nil %>
<div id="alert_box" class="alert_wrap">
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
</div>
<% end %>

Answer №1

let myTimer = setTimeout("myTimerFunction()", 3000);
$('#alert_box').mouseout( function () {
  myTimer = setTimeout("myTimerFunction()", 3000)
});

$('#alert_box').mouseover( function () {
  clearTimeout(myTimer);
});

let myTimerFunction = function () {
  $('#alert_box').fadeOut('fast');
}

// On click, fadeout
$("#close").click(myTimerFunction);
.alert_wrap {
padding: 0px 50px;
margin-top: 3px;
height: 5%;
background-color: rgba(255, 0, 0, .3);
border: 3px solid red;
grid-row-start: 2;
justify-self: center;
}
#alert_box {
  position: relative;
}
#close {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="alert_box" class="alert_wrap">
<p class="notice">This is notice text</p>
<p class="alert">This is alert text</p>
    <span id="close">X</span>
</div>

For the initial step, you can utilize the setTimeout function, and then upon mouseover or hover event, you can cancel the timeout function by using clearTimeout. This will prevent the fadeout from occurring.

When the mouse is moved away, you can set a new setTimeout to begin counting for 3 seconds again.

Furthermore, since you mentioned a click event, I included a close button that, upon clicking, immediately triggers the timeout function.

Answer №2

If you want to add some flair to your alert messages, try using CSS animations:

.notification_box {
  padding: 0px 50px;
  margin-top: 3px;
  height: 5%;
  background-color: rgba(255, 0, 0, .3);
  border: 3px solid red;
  grid-row-start: 2;
  animation: shake-alert 4s linear none;
  opacity: 0;
  transition: all .3s ease-in-out;
}

@keyframes shake-alert {
  0%,
  100% {
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
}

.notification_box:hover {
  opacity: 1;
}
<div class="notification_box">
  <p>You've got mail!</p>
</div>

Answer №3

This approach could be an alternative solution, although personally I prefer incorporating CSS transitions (especially utilizing the :not(:hover) pseudo selector).

const timer = setInterval(hideElement, 100); // interval function

function hideElement() {
  if ($('.notification_box:not(:hover)').length) { // check if the notification box is visible and not being hovered
    setTimeout(function() { // after 3 seconds
      if ($('.notification_box:not(:hover)').length) { // if still not hovered
        $('.notification_box:not(:hover)').fadeOut('fast');
        clearInterval(timer);
        handler = 0;
      }
    }, 3000);    
  }
}

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

Experimenting with HTML and CSS to enhance email presentation

I am currently developing a Django application that requires sending out Emails with HTML templates. These email templates include images and dynamic variables from the Django context. However, each time I make changes to the inline CSS or HTML, I have t ...

Issues have been encountered with the Angular Bootstrap accordion animation not functioning properly when closing in a production

After setting up Bootstrap in Angular app, I encountered an issue in production. When using the accordion feature with animation, the closing animation does not work when I run ng build --configuration production and view it on the local server. The openin ...

I am completely baffled as to the origin of this mysterious stylesheet in my Wordpress PHP code

I have been encountering an issue while updating my website where the original stylesheet seems to be persistent despite my efforts to replace it. I replaced the style.css file in my bluehost control panel and removed any custom css settings, but the old s ...

Capybara's visit function is inexplicably frozen

We have a robust cucumber suite for our Rails project, mainly utilizing Capybara and navigating through Firefox. Lately, we encountered a recurring failure that is causing some confusion. Here are the key details: During a specific point in the process ...

CSS - selecting elements that are greater than a specific criteria N

I have multiple <p> tags in the body of my HTML. I want to display only the first two paragraphs and hide all the paragraphs that come after. However, the code I'm using doesn't seem to work as expected. <html> <head> < ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

The issue of excessive body overflow arises upon opening multiple modals successively

I'm facing an issue with bootstrap modals. When I open the first modal, the body gets the class modal-open which is correct. However, when I click the button to close the first modal and open another one, the class is removed from the body even though ...

No matter what I try, connecting the CSS file to my HTML file just won't seem to work

I've been attempting to connect a CSS file to my HTML index file, but I can't seem to get it to work no matter what I try. I'm using VSCode. When typing the link from scratch, it auto-completes or shows up, indicating that it recognizes it. ...

HTML: Attempting to extract the inner div from the outer div and relocate it outside of the outer div

I am attempting to extract an inner div from an outer div and relocate it outside of the outer div. https://i.stack.imgur.com/NSS7B.png <div class="vc_gitem-zone-mini"> <div class="vc_gitem_row.............."></div> <div> I Would ...

How can I integrate checkboxes in a list view with jQuery Mobile?

How can I display the status of users with three different levels in a list view? I need to show whether they are attending or not, similar to the image provided. The issue is that currently the checkbox appears below the name, but I want it to be at the r ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

What is the most efficient way to transform HTML into React components effortlessly?

I have been attempting to automate the process of converting HTML into React components. I followed the link below to automatically convert HTML into React components: https://www.npmjs.com/package/html-to-react-components However, I encountered an issue ...

Leverage jQuery to retrieve information and fill in an HTML form

Seeking assistance with retrieving data based on a dropdown selection change. Specifically, choosing an Item ID from the dropdown and then populating textboxes and other dropdowns with values from the database. The other dropdowns already have assignment o ...

Tips for centering text inside a div using a separator

During my side project, I decided to use the angular material divider but encountered issues with aligning the text correctly. https://i.stack.imgur.com/zg1mu.png The problem can be seen in the image provided - the text on the right side is not aligned b ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

Create a unique margin using CSS only that will appear at the bottom of a flex-row container that scrolls

I'm trying to create a horizontal scroller with margins between each item and consistent margins at both ends. However, I'm noticing that the margin at the end of the container seems to be disappearing somehow. Is there a way to maintain the mar ...

Create a dialog box with rounded triangle corners

In the process of developing an application, we are incorporating a text display feature within a div that resembles a chat box direction, but with a curved style as depicted in the screenshot linked below. Desired design exemplified in purple Target des ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

Altering the ASP DropDownList's background color solely with CSS modifications

Is there a way to change the background colors of dropdownlists in my C# web app using CSS instead of specifying each one individually? In simpler terms, I'm trying to avoid having to write out code like this for multiple dropdowns: private void For ...