Tips for emphasizing the current element without disrupting existing styles

Is there a way to highlight an element with a border without causing it to shift? The script seems a bit glitchy when detecting mouse leaving the area.

I'm unable to override parent element properties like border or outline. I also can't use pseudo-classes with position: absolute due to potential differences in position values on the parent element.

For example, selecting top questions causes the button to align differently.before and after

document.addEventListener('mousemove', e => {
    var element = document.elementFromPoint(e.clientX, e.clientY);
    if (element.id === "_wrapper" || element.parentNode.id === "_wrapper" || element.tagName === "HTML" || element.tagName === "BODY") return;
    var parent = element.parentNode;
    var wrapper = document.createElement("div");
    wrapper.id = "_wrapper";
    
    // set the wrapper as child (instead of the element)
    parent.replaceChild(wrapper, element);
    // set element as child of wrapper
    wrapper.appendChild(element);
}, {passive: true})
 
document.addEventListener("mouseout", e => {
    var element = e.target
    if (element.id === "_wrapper") {
        // remove wrapper
        element.replaceWith(...element.childNodes)
        // element.outerHTML = element.innerHTML;
        // element.replaceChild(element.parentNode, element)
        // console.log(element, element.parentNode)
    }
})

var style = document.createElement('style');
style.innerHTML = `
#_wrapper {
    border: 1px solid;
}
`;
document.head.appendChild(style);

Answer №1

Give this a go. By utilizing the `border-box` value for the box-sizing property, the border size will be included in the total size of the element without affecting its previous dimensions.

#_container {
    border: 2px dashed;
    box-sizing: border-box;
}

Answer №2

First things first, let's address a small issue on line 1 of the code where you have a typo: "mouseove"

Secondly:

...it slightly moves the element...

To prevent borders from affecting an element's dimensions, you can use *{box-sizing:border-box}.

Below is a snippet of CSS that I always include in my projects to avoid such issues (you might want to do the same):

* {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  list-style: none;
  text-decoration: none;
  box-sizing: border-box;
}

body {
  overflow-x: hidden;
}

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

"JavaScript encountered an Uncaught TypeError: Cannot read property 'style' of undefined

Looking to create a local time clock using HTML, here is the code: <body> <div class="container text-center"> <div class="row"> <div class="col-xs-12 col-sm-6"> & ...

Attempting to delete a record in a Node.js Express MongoDB Jade application

I am facing a challenge with my application as I attempt to incorporate a button that can delete an entry containing a date and link. When I trigger the button, I encounter an error message stating: Error 404 not found. The goal is to input the date and li ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

What could be causing the data to not load from the database when the page is loaded?

My current setup involves a button that triggers a specific function upon loading. return ( <> <LikeButtonStyle onLoad={getUserData} onClick={addInfo}> <Image width="10px" height="auto" src="/ ...

Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style. This code snippet illustrates how the crawl is displaye ...

Hover to reveal stunning visuals

Can anyone help me figure out how to change the color of an image when hovered over using HTML or CSS? I have a set of social network icons that I want to incorporate into my website, and I'd like the icon colors to change when the mouse moves over th ...

Feeling trapped during the process of setting up a intricate jQuery Image Slider

I've hit a roadblock while trying to make changes to the slider located at THIS URL. In the current setup, each thumbnail corresponds to one main display image. Clicking on a thumbnail displays a single image and then proceeds to slide to the next th ...

Align the text to the center beneath the image using Jquery's append function

I am looking to showcase a collection of fruits and vegetables through images, with the names displayed centered underneath each image. Additionally, I want to implement jQuery append functionality so that the names only appear when a specific button is cl ...

Receiving a NaN output rather than a numerical value

Experiencing what seems to be a straightforward syntax error, but I'm unable to pinpoint it. Controller: $scope.startCounter = 3; $scope.startTimeouter = function (number) { $scope.startCounter = number - 1; mytimeouter = $t ...

Inject data into an Angular 2 template

Does anybody know of a method to pass variables to templates in Angular2? Suppose I have the following code snippet: <div *ngFor="foo in foos"> <ng-container *ngTemplateOutlet="inner"</ng-container> </div> --------------- <n ...

I am looking to have two elements positioned next to each other in equal dimensions, such as the reCaptcha feature

Could someone assist me in positioning these elements side by side, each taking up 50% of the screen? I'm unsure if this can be achieved while using the reCaptcha iFrame. <div class="g-recaptcha" data-sitekey="sitekey" style="transform:scale(0.5); ...

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...

Minimizing HTML code on the main page of WordPress is a crucial optimization technique

I implemented this code to compress the HTML output on my WordPress website. While it works perfectly on the main page and post pages, it's causing several issues in the admin section. function minify_html(){ ob_start('html_compress'); ...

Using percentages for CSS alignment and adjusting element widths

Greetings everyone! I have been struggling to align two divs - one on the right with a width of 30% and the other on the left with 70%. Despite my efforts, I have not been able to find a solution. I am hopeful that someone here can assist me. My setup inv ...

Using a foreach loop to showcase data in a table

My goal is to utilize the GitHub API to showcase all the issues present in my repository in a neat table format on my website. Despite my best efforts, I am facing difficulties in generating the table using a foreach loop. Below is the PHP code I am curr ...

CSS - Issues with transition smoothness on Safari

I am facing an issue with a simple font-size transition in Safari, causing stuttering while it works smoothly in Chrome and Firefox. I'm not sure if this is a Safari problem, a Webkit issue, or something else entirely. Any workaround suggestions would ...

"Trouble encountered while trying to display Angular in an HTML document

In my Angular project, there is a feature where a list of orders is displayed in one view. Each order is represented by its title only. When the user clicks on the title, they should be redirected to a new view showing the complete content of that particul ...

The highlight_row function seems to be delayed, as it does not trigger on the initial onClick but works on subsequent clicks. How can I ensure it works properly right from the first click?

I developed an application using the Google JavaScript Maps API to calculate distances between addresses. I've encountered a bug where the row in the table is not highlighted on the first click, requiring a second click for the highlighting to take ef ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

The CSS hamburger icon displayed in the browser features three bars of varying heights

Looking to create a hamburger icon menu using only CSS? Check out my implementation below which includes three span tags in the HTML document. .sidebar-toggle { display: inline-block; } .sidebar-toggle span { display: block; width: 1.5rem; heig ...