Determine the duration of hovering over a button using RxJS

Is it possible to track the total duration, in seconds, of each time a user hovers over a button? How can this information be aggregated and displayed?

var result = document.getElementById('result');
var source = Rx.Observable.fromEvent(result, 'mouseover');
var subscription = source.subscribe(
   function (x) {
    console.log('Hovered!');
   }
);

Answer №1

Based on my understanding of your needs, you will have to monitor both the mouse entering and leaving the element, then utilize an operator like scan to calculate the total time. One way to achieve this is by capturing the timestamp of the mouseover event and then sampling on the mouseout event:

var result = document.getElementById('result');
var mouseOver = Rx.Observable.fromEvent(result, 'mouseover');
var mouseOut  = Rx.Observable.fromEvent(result, 'mouseout');

mouseOver
  //Record the time when mouseover occurs
  .timestamp()
  //Wait for mouseOut event to trigger
  .sample(mouseOut)
  //Retrieve only the timestamp value
  .pluck('timestamp')
  //Obtain a new timestamp (after mouse out)
  .timestamp()
  //Calculate the time interval
  .map(x => x.timestamp - x.value)
//Add the new time interval to the running total
.scan((total, diff) => total += diff, 0)
.subscribe(x => console.log(x));

Answer №2

I devised an alternative approach that may not be the most efficient, but I believe it's worth sharing for its unique technique.

let counter = 0;

const source = Rx.Observable.interval(100)
  .map(() => '.');

const display = document.querySelector("#display");
const toggle = document.querySelector("#toggle");

let hover = false;

const mouseOver = Rx.Observable.fromEvent(toggle, "mouseenter")
  .map(e => {hover=true;});
const mouseOut = Rx.Observable.fromEvent(toggle, "mouseleave")
  .map(e => {hover=false;});

mouseOver //.filter(x => true)
  .flatMapLatest(() => source.takeUntil(mouseOut))
  .subscribe(x => {counter += 1; display.innerText = counter});

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 fetch request in a React application is not returning a response body, whereas the same request functions properly when made using Postman

My React app is successfully running locally with backend REST APIs also running locally. However, when I attempt to make a POST call to the REST API, the call goes through but the body appears to be empty. Below is a snippet of the sample code: const bod ...

I am struggling to retrieve a value from the angular.forEach function, the flag value is not being obtained. What could be

I'm having an issue with my controller.js file. I can't seem to access the value from the angular.forEach function, specifically the flagvalue isn't being retrieved. Is it because the scope of flagvalue ends when the forEach function complet ...

Struggling to grasp the concept of DOM Event Listeners

Hello, I have a question regarding some JavaScript code that I am struggling with. function login() { var lgin = document.getElementById("logIn"); lgin.style.display = "block"; lgin.style.position = "fixed"; lgin.style.width = "100%"; ...

Using jQuery to create a slider that triggers a separate function

As someone relatively new to jQuery sliders, I'm hoping for some patience as I navigate this! I'm aiming to utilize my updateData(input) function with varying input based on the slider value. However, I've discovered that using an if statem ...

Retrieve the keys stored within a complex array of objects

I am searching for a function that can transform my data, specifically an array of objects with nested objects. The function should only include keys with immediate string/number/boolean values and exclude keys with object/array values. For example: [ { ...

How can Ext JS 6.2 automatically expand the East panel when the West panel is triggered?

In my Ext JS v6.2 Grid application, I am faced with the task of ensuring that if the WestRegion panel is closed, the EastRegion panel should open automatically, and vice-versa. Being new to Ext JS, I initially attempted to achieve this using jQuery. Howeve ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Issue with Date Picker not properly storing selected date in MySQL database

My goal is to save the datepicker date to MySQL by selecting the date format using JavaScript. I have verified that the date format appears correct as YYYY-MM-DD when logging to the console. However, when I try to execute an INSERT query to MySQL, the date ...

Utilizing JQuery to extract the image title and render it as HTML code

I am currently facing an issue with displaying an image in my project. I want to hide the image using CSS (display: none) and instead, retrieve the value of its title attribute and display it within the parent div by utilizing JQuery. Despite knowing tha ...

Unable to invoke function on HTML element

Recently, I've ventured into writing jQuery-like functions in Vanilla JS. While my selectors seem to be working fine, I encounter an "is not a function" error when trying to call the append function on an HTML element. var $ = function(){ this.se ...

Error message: "Function is not defined"

Below is a snippet of my JavaScript code: $('td:eq(2)', nRow).html('<a class="critical" href="#" OnClick="toAjax(\''+aData[1]+'\', \''+aData[2]+'\');">'+aData[3]+'& ...

The functionality of ng-show becomes compromised when used in conjunction with ng-animate

Once the animate module is activated, the ng-show functionality seems to stop working. Even though the default value for the ng-show expression is set to false, the element is still displayed and the ng-hide class is not being applied. However, if I deac ...

Chrome compatibility problem with scroll spy feature in Bootstrap 3

Having trouble with scroll spy for boosters using the body method " data-spy="scroll". It seems to be working for some browsers like Edge and Google Chrome, but after multiple attempts, it still doesn't work for me. Even after asking friends to test i ...

Ordering ng-repeat in AngularJS using a separate arrayDiscover how to easily order your

Imagine I have an array containing keys in a specific order orderedItems=["apple","banana","orange]; and there is a JSON object that I want to display using ng-repeat but following the sequence specified in the array: {"fruits": { "apple":{ ...

Tips for incorporating a favicon in a React application

Having trouble adding a favicon to my React application. I followed the instructions in this post, but it's not working for me. I placed the favicon.ico file inside the public folder where index.html resides. This is how my directory structure looks ...

Using Array.Map() to retrieve the child array within a React component

Here is the data I have retrieved from an API: [ { "id": 1, "appName": "string", "defaultAction": "string", "defaultMessage": "string", "rules": [ { "id": 1, "version": "string", "brand": "string", ...

Enhancing WooCommerce by including additional text following the price for specific shipping methods

I need assistance with including a short message like "(incl. VAT)", following the shipping-price display on the checkout page. The challenge lies in ensuring that this message only appears for a specific shipping method within Zone 1 (zone_id=1), but I&a ...

Is there a way to attach a JavaScript event to a textarea without directly accessing it?

I am curious about how to incorporate the following code: onblur="hcb.watermark.blur(event)" onfocus="hcb.watermark.focus(event)" style="color: rgb(136, 136, 136); into a textarea with the id "HCB_textarea" and the class "commentbox hcb-shadow-r," withou ...

What could be causing the peculiar behavior I am experiencing when a child component attempts to display values from an object fetched in the parent component?

I am currently developing an Angular application and encountering a challenge when it comes to passing data from a parent component to a child component using the @Input decorator The parent component is named PatientDetailsComponent. Here is the TypeScri ...