Is there a way to update the value of an element that is continuously changing through a setInterval() function when hovering the mouse over it?

I am currently a novice working on developing a pomodoro timer. At the moment, when you click the button to start the timer, it switches to displaying the remaining time once activated.

One of the features I want to implement is the ability for users to hover over the displayed time to hide it and show the word "Pause" instead, all without disrupting the running timer in the background.

https://i.sstatic.net/6kZvz.jpg

My understanding is that I will need to achieve this using JavaScript (possibly jquery .hover()). However, my challenge lies in making this interaction only possible while the timer is active, as it constantly updates every second. I have tried defining the hover functions within the setInterval callback function, but this resulted in unexpected outcomes that were not intended.

Another approach I thought of was to show a hidden div with absolute positioning above the timer whenever the user hovers over it. But I am unsure of how to execute this idea.

If someone could assist me in bringing this concept to life, I would greatly appreciate it.

code pen: http://codepen.io/meek/pen/zradga

function activateTimer() {
    if(inProgress === false) {
      inProgress = true;
      updateTimer(session);
      interval = setInterval(function() {
        if(session > 0) {
          focusSession();
          session -= 1;
          updateTimer(session);
        }
        else {
          if(breakTime > 1) {
            focusBreak();
            breakTime -= 1;
            updateTimer(breakTime);
          }
          else if (breakTime == 1){
            breakTime -= 1;
            updateTimer(breakTime);
            session = sessionLength * 60;
            breakTime = breakLength * 60;
          }
        }
      }, 1000);

      $('#timer').removeClass('hovergreen');
      $('#timer').addClass('hoverred');
    }
    else {
      inProgress = false;
      clearInterval(interval);

      $('#timer').removeClass('hoverred');
      $('#timer').addClass('hovergreen');
    }
  }

This function contains most of the key functionalities of the timer and requires some tweaking to add the desired hover effect.

Answer №1

To update your HTML, simply include a div element with the class name pause:

<div class="meter">
   <div class="pause">Pause</div>
   <div class="meter-container"></div>
   <div class="base"></div>
   <div id="timer" class="timer btn hovergreen">START</div>
</div>

Next, add the following CSS styling:

.meter{
    position: relative;
}
.meter .pause{
    position: absolute;
    display: none;
}
.meter:hover .meter-container, .meter:hover .base, .meter:hover .timer{
    visibility: hidden;
}
.meter:hover .pause{
    display: block;
}

Answer №2

After some experimentation, I managed to find a solution. I decided to create a div with an absolute position called "pause" and set its display property to none.

The key was to check if the variable inProgress (which is true when the timer is running and false when it's not) is also true within a hover callback function for both the timer and the pause div. This prevents any awkward situations where hovering over the timer triggers the appearance of the hidden pause div, only to have it disappear immediately because the cursor moved away.

Here's how I implemented this:

$('#timer').hover(function(){
    if(inProgress) {
      $('#pause').css('display', 'block');
    }
  },
                    function() {
    $('#pause').css('display', 'none');
  });

  $('#pause').hover(function() {
    $('#pause').css('display', 'block');
  },
                   function() {
    $('#pause').css('display', 'none');
  });

You can view the code on CodePen here: http://codepen.io/meek/pen/zradga

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

When selecting a new tab in HTML, the current page position remains unchanged. However, I would like the page to automatically scroll to the

In the design of my website, I have incorporated buttons that are linked to various pages using navigation tabs. However, when these buttons are clicked, the view maintains its position on the new page (e.g., halfway scrolled through the page). Instead o ...

When implementing dynatable with Meteor, the outcomes may vary between the demonstration in a fiddle and the actual application

Here is the fiddle I created for this question: https://jsfiddle.net/ereday/82wzwem8/2/ In the fiddle, you'll notice that the table header has a green background. Now, let me share the code snippet from my meteor project: simple-todos.html <head ...

What is the best way to find the initial row of an HTML table with Angular?

When working with the code snippet in my doSomething method shown below, I am curious about how to accurately identify the rowIndex. <tr ng-repeat="a in mydata"> <td><b>{{doSomething(mydata.name)}}</b></td& ...

Can CSS be utilized to consistently display text in a uniform manner?

Currently developing a unique Qur'an app for Muslims, standing out from the already existing ones in the market. There are two common types of Qur'an apps available: one that replicates the exact look of a physical copy, page by page, using imag ...

Time taken to execute all the tests using the karma runner

We have recently transitioned to running unit tests remotely using browserstack across multiple browsers and operating systems with the help of the karma-browserstack-launcher plugin. The current output of our test run appears as follows: $ grunt unit:re ...

Using the cURL command to retrieve script content

Currently, I am utilizing cURL to access a specific website. However, I have encountered an issue where the content I require is generated by a script: function Button(){ ... document.getElementById("out").innerHTML = name; } <p id="out"></p> ...

Guide on sending a JSONArray from ajax to the controller

Currently working with Spring MVC in Java, I am faced with an issue where I am attempting to pass a List from JavaScript to the controller as a JSONArray. However, upon reaching the controller, it is either showing up as an empty array or null. Would grea ...

Manifest file for jQuery plugins/npm

Have you ever wondered why jQuery plugins come with their own manifest file .jquery.json instead of utilizing npm and its package.json? It seems like dependencies management and hosting files could be handled by npmjs.org effectively... Is anyone else cur ...

Results not showing up

After attempting to incorporate the scores into a table, I am facing an issue where they are not displaying. Can anyone offer assistance with this problem? I am currently hosting on GitHub Pages. File: https://raw.githubusercontent.com/Eternal-Network/Ete ...

Fade the current Div out and fade in the following Div while also animating its child element

Looking to achieve a fade in and out effect for 3 divs, with the child element animating its way up from the bottom right once the divs have faded in. I've been working on it but haven't made much progress, does anyone have any ideas? Check out ...

What is the method for exporting a variable from a module in JavaScript?

Based on information from this forum post, it is possible to export variables from one module to another in JavaScript: // module.js (function(handler) { var MSG = {}; handler.init = init; handler.MSG = MSG; function init() { // Initialize t ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

How can I retrieve JSON keys and values in JQuery and append them to a list (ul)?

Can you please review this jsFiddle link: http://jsfiddle.net/xY7tx/3108/ Whenever I use getJSON in the provided example, why does the fail part always get executed? I am seeking assistance on how to extract the key and value from the JSON file using jQu ...

Is it possible to set specific points within a Points object in THREE.js to be transparent or invisible?

I am working with a Three.js Points object that holds information for displaying multiple points in 3D space. I am looking for a way to dynamically hide certain points, but I am uncertain of the process. The PointsMaterial used has xyz data stored in poin ...

Error: Module 'fs' does not export the function 'existsSync' as requested

When I simulate the behavior of the fs module jest.mock('fs', () => { return { default: { readFileSync: () => { return CONTENT_DATA; }, existsSync: () => {}, }, }; }); Then I attempt to dynamically ...

How come the 'npm install canvas' command did not generate a JavaScript file as expected?

My venture into the world of node packages has just begun. I recently tried installing canvas to my project using this command: npm install canvas Prior to successfully executing the installation, it was necessary for me to first install gtk and cairo by ...

Enhancing Image Quality with jspdf and Html2Canvas

We are currently utilizing jsPDF and HTML2canvas to create PDFs, however, we have noticed that the image resolution is quite high. Is there a method available to obtain low-resolution images using jquery, javascript, jsPDF, and html2canvas? function addE ...

Arrangement of Axes in Google Graphs

I have a basic form where users can input data through drop-down selectors. There are 10 questions, each with a rating out of 10. The entered data is then used to generate a Google graph on the same page. Although the graph populates correctly, the axis ...

What is the most effective method for optimizing websites that do not respond to changes in window size

I've developed a website that is not responsive (it's more of an "experimental/artistic" site with a lot going on the screen, making it difficult to make it responsive..) I have decided not to cater for mobile phones, but I would like the site t ...

Enhance the functionality of jQuery within a React application by creating custom chained jQuery functions

Before criticizing me, please hear me out: I understand that React can replace a majority of the functionalities provided by jQuery. However, I need specific interactions to occur when users hover over items, and as far as I know, React does not support th ...