Identifying when the mouse hovers over a hidden element

Is there a way to make events trigger for <mark> elements under a <textarea>? I've tried adding mouseover listeners, but they don't seem to work because of the <textarea>.

I need the <text-area> to function normally, so using pointer-events: none is not an option.

Please provide a solution without jQuery.

Link to example: https://jsfiddle.net/aewc13nm/

Answer №1

It seems you are in search of a solution that does not rely on CSS or layering of elements/siblings. If that's the case, I have come up with a method to create a custom mouseover/out functionality. This approach involves monitoring global mouse movements on the window and checking every ~17ms if we are moving across the boundaries of the designated element (I also included a custom event in case there are intricate nested elements involved, although it's not mandatory):

FIDDLE

To differentiate between various mouseover/out events, I've incorporated Math.random.

!function(){
  var mark = document.getElementsByTagName("mark")[0],
        mouseout = true,
      mouseover = false,
      customMouseEvent = new CustomEvent(
        "customMouseEvent",
        {
            bubbles:false,
          detail:{
            mouseout:function(){return mouseout},
            mouseover:function(){return mouseover}
          }
        }
        );
      mark._lastGesture = "mouseout";
    window.addEventListener("mousemove",function(e){
    if(mark._busy){return}
    mark._busy = true;
    window.requestAnimationFrame(function(){
      var rect = mark._rect || (mark._rect = mark.getBoundingClientRect());
      if(
        (e.clientX - rect.left < rect.width)
        && (e.clientX - rect.left > 0)
        && (e.clientY - rect.top <= rect.height)
        && (e.clientY - rect.top > 0)
      ){
        mouseout = false;
        mouseover = true;
      } else {
        mouseout = true;
        mouseover = false;
      }
      mark.dispatchEvent(customMouseEvent);
      mark._busy = false;
      setTimeout(function(){delete mark._rect},17);
    });
  });
  mark.addEventListener("customMouseEvent",function(e){
    if(e.detail.mouseover() && this._lastGesture !== "mouseover") {
        this._lastGesture = "mouseover";
        document.getElementById("feedback").textContent = "Mousover! " + Math.random();
    } else if (e.detail.mouseout() && this._lastGesture !== "mouseout") {
        this._lastGesture = "mouseout";
      document.getElementById("feedback").textContent = "Mousout! " + Math.random();
    }
  })
}();

Answer №2

Consider utilizing contenteditable="true" in place of <textarea>
Just like this

function increaseFontSize(x) {
    x.style.fontSize = "24px";
}

function decreaseFontSize(x) {
    x.style.fontSize = "16px";
}
.text-input-container {
    border: 1px solid #000;
}

div.editable {
    width: 300px;
    height: 200px;
    padding: 5px;
}
<div class="text-input-container">
  <div contenteditable="true">
    Lorem ipsum dolor sit amet.<br>
    consecte, sed do <strong>tur adipiscing elit</strong> eiusmod tempor incididunt ut labore et dolore.
    <br>there is a  at the end?
    <br>tur adipiscing elit.
    <br>
    <br><mark onmouseover="increaseFontSize(this)" onmouseout="decreaseFontSize(this)">Great</mark>
  </div>
</div>

Answer №3

To enhance the visual display, consider including z-index: 1 in the span tag.

function makeBigger(x) {
    x.style.fontSize = "24px";
}

function makeSmaller(x) {
    x.style.fontSize = "16px";
}
textarea {
    border: none;
    outline: none;
    background-color: transparent;
}
textarea, span {
    position: fixed;
    font-size: 1rem;
    font-family: monospace;
    padding: 5px;
}
span {
    z-index: 1;
    color: transparent;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Web Page Example</title>
  </head>
  <body>
    <textarea id='content'></textarea>
    <span>Greetings <mark onmouseover="makeBigger(this)" onmouseout="makeSmaller(this)">world</mark>!</span>
  </body>
</html>

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

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Error: Attempting to access 'toString' property on an undefined value - redis

const updateLeaderboards = async () => { try { const users = await User.findAll(); const leaderboardData = []; users.forEach((user) => { // Add user data to the leaderboardData array in the required format leaderboardData.p ...

Executing cross browser testing in Node JS consecutively within a single session: A step-by-step guide

When conducting cross-browser testing, I prefer to run the tests individually rather than all together in one session. This way, I can ensure that all test results are accurately logged and generated into a single HTML report at the end of each session. I ...

The EJS is causing a problem with linking the style sheet

Currently, I am in the process of familiarizing myself with ejs, express, and node js. Facing an issue while trying to link my style sheet to my header, below is the code snippet and here is a https://i.stack.imgur.com/0BEIn.png. Utilizing include for bo ...

A guide on layering .ogg video with .png image using HTML5 and CSS3

I am having difficulty achieving the desired effect, even when using z-index and position:absolute. My goal is to overlay a .png image on top of a video, while still allowing the transparent parts of the .png file to reveal the video playing in the backg ...

What is the best way to rotate my geometry around the center in react-three-fiber?

Working on a personal side project where I'm utilizing react-three-fiber. The issue lies in the code below, which is responsible for rendering a text geometry with the text "Test". However, instead of rotating around its center, the Text Geometry appe ...

Is there a way to accelerate the webpack bundling process when using React during development?

Forgive me for what may seem like a silly question, but I am just beginning to explore the world of JavaScript and React. In my project, I am using React on the frontend and Django on the server side. Currently, I am unable to use React routing, so I have ...

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...

Angular directive: inability to pass ng-repeat item through isolate scope

I am currently working on a directive that has an isolate scope. The template of the directive includes an ng-repeat on an element, along with the following code snippet: ng-click="selection(item)" Within the directive's scope definition, I have spe ...

Retrieving selected option value in React

I am currently using Material UI for my React application and I am encountering an issue with getting the value of a select form. Initially, I had success with the following code snippet: <select name="role" value={props.role} onChange={props.handleIn ...

What are some steps I can take to diagnose why my Express server is not receiving POST requests from my HTML form?

Struggling with an unexpected issue on my website where the form submission is not triggering the POST request to my Express server. I've set up a MongoDB database and created a HTML form to store user data, but something seems to be amiss. HTML: & ...

retrieving POST form data with express.js and passport.js

After successfully creating a chatroom, I encountered an issue when transitioning the system to use only unique identifiers (UIDs). Here's a breakdown of how it operates: Upon signing up, a user receives a UID that is stored in the database along wit ...

Personalize the highcharts tooltip to display date and time

I'm working on a new project where I need to display a graph like the one you can see here: http://jsfiddle.net/Kc23N/ One issue I am facing is that when clicking on a point (tooltip), I want to show a date in a readable format rather than just the v ...

Unlocking Angular 10: Harnessing the Power of JWT for Seamless

I am encountering an issue with JWT login in angular. Although I have successfully logged in and saved the token, my frontend isn't reflecting the changes Auth.service.ts import { Injectable } from '@angular/core'; import { HttpClient, Http ...

Is there a way to display the button just once in a map function while still retaining access to the iteration value?

Utilizing formik within material-ui for a form has been quite productive. I've implemented a map function to print text fields and managed to display the Submit button only once by targeting the index. However, there's an issue when attempting to ...

Utilizing JQuery to populate DIVs with JSON information

Hey! I recently received some helpful advice from a coding expert, and now I'm in the process of restructuring my code based on these recommendations: When using $.each(), you have the option to return true or false. If you return false, the loop wi ...

Disable browser suggestions in Material UI's Autocomplete component

Encountering an issue with Material-ui Autocomplete: import Autocomplete from "@material-ui/lab/Autocomplete"; Currently using it in: <Autocomplete id="checkboxes-tags-demo" autoComplete={false} options={sta ...

Transitioning code from gatsby to nextjs has caused an issue with the aws-sdk integration

I have successfully integrated the aws-sdk with Gatsby by using a .env file to upload a file to an S3 bucket. Now, I am in the process of migrating this functionality to Next.js, but I'm encountering an error in Next.js. Uncaught (in promise) Credent ...

Is there a live password verification tool available?

Currently, I am conducting some initial research for my school's IT department as a student employee. The students at our institution are required to change their passwords every six months, but many of them struggle with the various password regulati ...

Send a vanilla JavaScript ajaxForm submission by completing the form

I am currently in the process of integrating JavaScript from an iOS application into a web application. I have control over the code for both apps. My objective is to develop a JavaScript function that can receive input from a barcode scanner, populate a w ...