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

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

How can you receive a file through AJAX response?

I have a standard Ajax function that I regularly use to call a specific function within my node.js server. This particular function is responsible for retrieving a file (usually in xls format) from the server and streaming it back to the client. Below is ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

Switch to using addresses instead of latitude and longitude coordinates when utilizing the Google Maps API

I am looking to utilize Google Map Markers to indicate the locations where our services are offered. The code I have created using latitude and longitude is functioning properly, however, for my project I need to display city names instead of lat/long ...

Issue with hasClass and addClass not working as expected

Why isn't the script below adding a class (.active) to .global-header when .navigation.primary has a class of .active? JS if($(".navigation.primary").hasClass("active")) { $('.global-header').addClass('active'); } HTML < ...

Issue with showing Angular directive

I've been working on implementing an angular dropdown list with Bootstrap. The functionality includes a directive that allows the user to select a menu option from the dropdown and receive an alert message. To see the implementation in action, I have ...

Enhance Your Website with HTML and JavaScript

Here is the code snippet I am working with: sTAT **javascript** var acc = document.getElementsByClassName("item-wrapper"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function(){ this.classList.toggle("selected"); this.nextElementS ...

C# web service is unable to return a specific value

I attempted to use a basic web service (just to test if the value will populate in the JavaScript code). I experimented with a very simple snippet, but it kept returning 'undefined'. Can you offer some guidance? I have tried several solutions wit ...

Is it possible for a JavaScript environment to restore function normally after modifying the [[Prototype]] of an object?

After thoroughly reviewing the MDN disclaimers and warnings, as well as an enlightening discussion in a popular online forum, I still find myself seeking answers. This question arose from a previous exchange, which can be found here. Imagine if I were to ...

The call to the hook is invalid. In order to use hooks, they must be called within the body of a function component in

So, in my upcoming application, I am incorporating the react-google-one-tap-login library which features the useGoogleOneTapLogin hooks that need to be invoked within a React component. However, when I attempt to use it in this manner: func() { useGoogle ...

Achieving opacity solely on the background within a div class can be accomplished by utilizing CSS properties such

Whenever I adjust the opacity of my main-body div class, it results in all elements within also becoming transparent. Ideally, I would like only the gray background to have opacity. See below for the code snippet: <div class="main1"> content </di ...

Automatically selecting a row within Material-UI's data grid using React code

Currently, I am in the process of developing a React web application and utilizing DataGrid from Material-UI by Google. The grid displays based on the user's selection from a select list (e.g., if the select list consists of fruits and the user choose ...

Challenges in the Knockout Framework Due to Synchronization Issues

Recently, I've encountered a slight problem with race conditions in my code. Utilizing Knockout.Js to collect information for user display has been the cause. The issue arises when a dropdown needs to be created before a value can be selected. Typica ...

Angular Promises - Going from the triumph to the disappointment callback?

It seems like I might be pushing the boundaries of what Promises were intended for, but nonetheless, here is what I am attempting to do: $http.get('/api/endpoint/PlanA.json').then( function success( response ) { if ( response.data.is ...

Resetting form fields when clicking the "Next" button with the FormToWizard jQuery Plugin

I am in the process of developing a lengthy form using the jQuery plugin called formToWizard. Within one of the fieldsets located midway through the form, there are hidden fields that are displayed upon clicking a button. The strange issue I am encounterin ...

What is the best way to combine a custom CSS class and a bootstrap class to style an element in next.js?

In the following example, the CSS class is imported and then applied to the element: import customStyles from "./Home.module.css"; <div className={(customStyles.collection, "card")}> Although they work individually, when combined as shown above, t ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

There seems to be an issue with Jekyll where it is failing to generate HTML for Markdown pages

I recently delved into the world of Jekyll to transfer my blog over to GitHub Pages. Utilizing a local Jekyll tool (jekyll 3.1.3) with the neo-hpstr-jekyll-theme as a starting template on my Windows system. While the entry point (index.html in root) and p ...