After 30 seconds of inactivity, apply the CSS once, then remove it before repeating the process

I've got a unique little CodePen with an animation that I want to execute only if the user hasn't clicked on the <div class="someDiv"> for 30 seconds.

My question is, can someone guide me in the right direction so that when someone doesn't click on:

<div class="someDiv">
</div>

...for 30 seconds, this CSS will be applied (ONCE) by appending an id, similar to

$(".someDiv").attr("id", "#theBounce");
and removing it in a reverse manner.

#theBounce {
  background-color:red;
  width:50px;
  height:50px;
  margin-left:auto;
  margin-right:auto;
  margin-top:5%;

  -moz-animation: bounce 1.5s infinite;
  -webkit-animation: bounce 1.5s infinite;
  animation: bounce 1.5s infinite;
}

@-moz-keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    -moz-transform: translateY(0);
    transform: translateY(0);
  }
  40% {
    -moz-transform: translateY(-30px);
    transform: translateY(-30px);
  }
  60% {
    -moz-transform: translateY(-15px);
    transform: translateY(-15px);
  }
}
@-webkit-keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }
  40% {
    -webkit-transform: translateY(-30px);
    transform: translateY(-30px);
  }
  60% {
    -webkit-transform: translateY(-15px);
    transform: translateY(-15px);
  }
}
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    -moz-transform: translateY(0);
    -ms-transform: translateY(0);
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }
  40% {
    -moz-transform: translateY(-30px);
    -ms-transform: translateY(-30px);
    -webkit-transform: translateY(-30px);
    transform: translateY(-30px);
  }
  60% {
    -moz-transform: translateY(-15px);
    -ms-transform: translateY(-15px);
    -webkit-transform: translateY(-15px);
    transform: translateY(-15px);
  }
}

This means that a click will reset the script's counter, and not clicking for 30 seconds will apply the CSS for at least 1.5 seconds, then remove it, and start the timer again. I'm struggling to get this to work, especially the timing/reset on click part.

A link, an idea, a suggestion. Any help is appreciated. Thank you.

Answer №1

If you're looking for a solution, I recommend using setTimeout.

When the document is loaded, initiate your setTimeout by setting a variable to hold the timer that will add your content after a specified number of milliseconds. Then, update the timer variable with a new setTimeout for a different amount of time.

var myTimer;
myTimer = setTimeout(function(){ /*execute code after 3 seconds*/ }, 3000);

If at any point you want to stop the timer when an action occurs, you can clear the timer using:

clearTimeout(myTimer);

Here's an illustration:

(function () {
  var myTimer,
      announce = document.getElementById("announcement"),
      button = document.getElementById("stopIt");
  function firstTimer () {
      announcement.innerHTML = '';
      myTimer = setTimeout(function () {
          populateContent();
      }, 500);
  }
  function populateContent () {
      announcement.innerHTML = 'press the button!!';
      myTimer = setTimeout(function () {
          firstTimer();
      }, 500);
  }
  button.addEventListener('click', function () {
    clearTimeout(myTimer);
  });
  firstTimer();
}());
#announcement {
  border: 1px solid red;
  height: 5ex;
  width: 30%;
}
<div id="announcement"></div>
<button type="button" id="stopIt">Stop!!</button>

Answer №2

While I may not be an expert on this topic, one potential solution could involve utilizing the setTimeout function in Javascript.

Learn more about setTimeout here

If we take a look at the first example provided on that page, it might offer some insight into achieving your desired outcome. Here's a suggestion that has not been tested:

HTML:

Live Example

Set CSS bounce after 30 seconds

Reset timer

Javascript: var timeoutID;

function setBounce() {
  timeoutID = window.setTimeout(bounceIt, 30000);
}

function bounceIt() {
  // Code to identify the bounce div, apply the specified CSS style,
  // and then establish a new timeout on the CSS to remove the style after 1.5s

}

function unbounceIt(bounceTimeoutID) {
  window.clearTimeout(bounceTimeoutID);
}

function resetBounceTimer() {
  window.clearTimeout(timeoutID);
}

This approach could potentially lead you in the right direction towards resolving your issue.

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

The function 'success' in Ajax/jQuery is essential for handling successful responses

I'm encountering an issue with displaying a value retrieved from the success function of my Ajax call. The code in question is shown below. $.ajax({ type: "POST", url: "http://localhost/practical 8/checkuser.php", data: form_data, suc ...

index() jQuery function is not

Upon clicking on an element with the class 'sections', I expect to see an alert displaying its class index, however, it appears to be showing an incorrect number. For example, if I click on the first div element with the class 'sections&apo ...

It is not possible to update a component while another component is being rendered. To identify the erroneous setState() call within the `MyApp` component

Whenever I navigate from the main page to the login page, I encounter this error. The Header component is used as a child component throughout my app. The error message reads: Cannot update a component (Header) while rendering a different component (MyApp ...

The 'blur' event in jQuery is not functioning as expected for file input fields

I am experiencing an issue with a form on my website. The form saves the record on each field blur event, but I noticed that when I select a file for the file field, it also saves the record, which is not the behavior I expected. I want the save action to ...

At what point is the rendering process of ng-switch completed?

I am currently utilizing ui-router and facing a challenge in instantiating a widget that requires a DOM element specified by its id as a parameter. The specific DOM element is nested within a <div ng-switch>, and I need to ensure the widget construct ...

Select the card if the input spinner value is greater than zero

Hello, I am currently working on a front-end tool for quoting purposes. The user will need to click on a card and select which product they would like to add to their basket. There is also an input section available for the user to specify the quantity usi ...

Is nesting possible with the &:extend function in LessCss?

I've recently been exploring the Less &:extend feature. My goal is to nest multiple extends - essentially extending a class that itself extends another class. However, after testing it out, I'm not sure if it's working as expected. It ...

NG-Bootstrap Navigation Bar- dynamic hamburger icon animation

I have been trying to implement an animated hamburger animation on the navbar using ng-bootstrap and Angular, but so far I have had no success. While the Navbar does collapse as expected, it lacks the animation and transformation into an 'x'. I w ...

What is preventing me from stopping the setInterval using window.clearInterval?

Below is the code I have written using window.setInterval and window.clearInterval. The window.setInterval function works fine, but when I attempt to call window.clearInterval, I encounter an error stating that intervalId is not defined. Is there a way t ...

Creating dynamic form groups that allow for the addition and removal of forms while assigning unique identifiers and names to each input field

I am currently immersed in the development of a sophisticated CMS system. My main objective is to dynamically add and remove form inputs using JavaScript upon clicking a button, with the ultimate goal of submitting the data into a database via PHP script. ...

What is the most effective way to transfer visitor hits information from an Express.js server to Next.js?

I've developed a basic next.js application with an express.js backend. What I'm aiming for is to have the server track hits every time a user visits the site and then send this hit count back to the next.js application. Check out my server.js cod ...

I am facing an issue where the PHP header redirection stops working after implementing event.preventDefault() on form submission

After successfully implementing jQuery in my signup page to handle and check the form fields, I encountered an issue where the header("location: ../****.php") no longer redirected me to another page upon clicking submit. Instead, it loaded the new page on ...

Tips for partitioning an element using Selenium and Appium when it lacks a distinctive ID, class, package, or resource identifier:

I am currently trying to determine if I am receiving the expected response from a text message. In order to do this, I need to access the text view of the incoming message. The challenge I am facing is how to distinguish between the received text and the s ...

Assign a value of an empty string to the attribute

My goal is to use jQuery to toggle the required attribute on fields. Initially, on page load, I add the required attribute to the necessary elements like this: $("[data-required]").attr("required", ""); Then, I have a toggle ...

Creating a centered floating card within a div that shrinks to fit its contents: A CSS how-to guide

I am facing a challenge with positioning a floating card that needs to be centered over the parent div (which happens to be selectable because it's a map). So far, I have only managed to achieve this by setting a fixed width for the card using the fo ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

CSS background image that will not be affected by padding-top

Is there a way to make a background image override the top padding on the first section of a website? I have set padding-top to separate the first title from the navbar, but now I want the background image to take precedence. Thank you! Using HTML: < ...

Is there a way to retrieve object data without using the map JS function?

Currently, I am delving into a project involving React, Redux, and JS. The tutorial I am following incorporates a dummy object within the redux store as illustrated below. const initState = { posts:[ [ {id: '1', title: 'Fi ...

Guide on resizing a ReactJS component for optimal browser display

Is there a way to resize a pre-existing React component within a browser that already has predetermined height and width? componentDidMount(x,y,z){ this.setState({height:window.innerHeight+'px'}); } I'm unsure if this approach is the corr ...

Step-by-step guide on integrating Bulma page loader extension as a Vue component

Is there a way to integrate the Bulma-extension page-loader element as a Vue component in my project? I attempted to import page-loader.min.js and use it, but unfortunately, it didn't work as expected. <template> <div class="steps"> ...