Stop objects from shifting while easily applying a border

I have a code that adds a red border around elements when you mouseover them and removes it when you mouseout.

However, the elements jump around when the border is added because it changes their dimensions. Is there a way to stop this jumping behavior?

document.addEventListener("mouseover", eOnMouseOver, true);
document.addEventListener("mouseout", eOnMouseOut, true);

function eOnMouseOver(e) {
  e.target.style.border = "2px solid red";
}

function eOnMouseOut(e) {
  e.target.style.border = "";
}
<div style="border:1px black solid;">Mouseover me</div>
<a href="#">Mouseover me</a>

Answer №1

Indeed, there is a solution for this. To achieve the desired effect, you can utilize box-sizing: border-box along with vendor prefixes. Here's an example to clarify:

document.addEventListener("mouseover", eOnMouseOver, true);
document.addEventListener("mouseout", eOnMouseOut, true);

function eOnMouseOver(e) {
  e.target.style.outline = "2px solid red";
}

function eOnMouseOut(e) {
  e.target.style.outline = "";
}
* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  -o-box-sizing: border-box;
}
<div style="border:1px black solid;">Hover over me</div>
<a href="#">Hover over me</a>

Alternatively, you can achieve the same effect without using JavaScript by utilizing CSS pseudo-classes, like so:

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-sizing: border-box;
  -ms-sizing: border-box;
  -o-sizing: border-box;
}

*:hover {
  outline: 2px solid red;
}
<div style="border:1px black solid;">Hover over me</div>
<a href="#">Hover over me</a>

Answer №2

Have you considered using a box shadow instead? This can have no impact on your layout, is purely aesthetic, and preserves the border property of your div:

document.addEventListener("mouseover", eOnMouseOver, true);
document.addEventListener("mouseout", eOnMouseOut, true);

function eOnMouseOver(e) {
  e.target.style.boxShadow = "0 0 0 2px red";
}

function eOnMouseOut(e) {
  e.target.style.boxShadow = "none";
}
<div style="border:1px black solid;">Hover over me</div>
<a href="#">Hover over me</a>

Answer №3

Set a transparent border on an element, and change the border color to red when it is hovered over

div,
a {
  border: 1px solid transparent;
}

div:hover,
a:hover {
  border-color: red;
}
<div>Move mouse over me</div>
<a href="#">Move mouse over me</a>

Answer №4

function onMouseEnter(e) {
  e.currentTarget.style.border = "2px solid red";
  e.currentTarget.style.marginLeft = "-3px";
  e.currentTarget.style.marginTop = "-3px";
}

function onMouseLeave(e) {
  e.currentTarget.style.border = "";
  e.currentTarget.style.marginLeft = "";
  e.currentTarget.style.marginTop = "";
}

Give it a shot. The margin adjustment should help keep the element in place when applying the border. This approach has not been tested yet.

UPDATE: Another alternative is to try this method...

function onMouseEnter(e) {
  e.currentTarget.style.border = "2px solid red";
}

function onMouseLeave(e) {
  e.currentTarget.style.border = "2px solid transparent";
}

Then, set the border in the onMouseLeave(e) function to prevent jittering on the initial hover event.

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 value of a Vue.js directive expression is consistently found to be undefined

I created a compact jsfiddle to show how to access directive values within the bind function. However, it seems to always return undefined. Check out the demo here! bind: function(){ console.log(this.value); this.el.innerText = this.value; } ...

Simulating dynamic route parameters in the Next 13 application directory

I am currently working with Jest and testing library to conduct unit tests on my NextJS application. I am facing difficulties in rendering a page on a dynamic path. Here is the code for my page/component: export default async function MyPage({ params }: { ...

Can anyone recommend a high-quality jQuery lightbox replica?

Key Features Needed: Customizable with CSS Capable of handling forms, not just images Extensively documented Please provide any recommendations and suggestions for suitable options. Thank you in advance ...

Which specific jQuery functionality was made visible?

When it comes to jQuery, how is it exposed? // Expose jQuery to the global object window.jQuery = window.$ = jQuery; However, there are in fact two versions of jQuery: var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( s ...

Mobile view div failing to fill remaining space

When viewing my website on a mobile device, the heading in the div tag is not occupying the remaining space like it does on desktop. The heading is an h4 tag inside a div tag for mobile view. If you want to check out my website in inspect mode, here is the ...

What is the best method to remove the x and up/down arrow components of an input date field?

My main objective is to have the orange triangle display in the box, but I'm unsure if CSS or another method is needed to remove the two elements on the left side of the triangle. Is there a way to achieve this? Currently, I am using the input type d ...

Issue with cancelling a file upload is not functioning properly on Internet Explorer

My experience with file uploads in Internet Explorer is causing some issues. While other browsers work smoothly when canceling file uploads, Internet Explorer seems to have a different behavior. In other browsers, clicking the "Cancel" button during a fil ...

Only one instance of a div with a table cell will function properly

I am facing an issue where I created a div with display:table-cell; and it appears as shown in the first picture, which is what I want. However, when I add another div, it changes to look like the second picture. All I want is for the text to be in the mid ...

Ensuring security against cross site scripting attacks on window.location.href

Currently, I'm utilizing window.location.href to redirect the page to an external URL: <Route exact path={rootUrl} component={() => { window.location.href =`https://${window.location.hostname}/www/testurl?google=true`; return null; }} /> How ...

Retrieving and transforming data from a JSON format using Regular Expressions

Hello there, I have a task that requires extracting data from the token_dict object received through the api and converting it. Here's an example: "token_dict": { "0x13a637026df26f846d55acc52775377717345c06": { "chain&qu ...

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...

When the user clicks, show a designated search result in a separate container

I've been developing my Angular cocktail application, and I've reached a point where I can display all the cocktails in my database (only showing names). Now, I want to implement a feature where if I click on a specific cocktail, its full content ...

Storing JavaScript variables in a database: A step-by-step guide

For the past few days, I've been working with CakePHP and trying to save a javascript variable into a MySQL database using AJAX (jQuery). Here's the code I've been using: <!-- document javascripts --> <script type="text/javas ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

https://i.sstatic.net/0jyFI.png There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.u ...

Is there a way to modify the log() function to handle multiple arguments?

Recently, I've been utilizing this logger in node.js: // Found on stackoverflow: https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color function logC(text) { console.log('\x1b[36m%s\x1b[0m', text); ...

Utilizing Vue.js to incorporate the isActive property to the class name within a v-for loop, along with implementing dynamic class names

I am currently using a loop to iterate through some data in my store.js file, and everything is functioning as expected. However, I would like to add a condition to check if the Vue instance is active before applying a specific class to the polygon element ...

Update the document by sending the data and making changes based on the AJAX response

Currently, I am avoiding using jQuery and trying to work with the following code in PHP: <?php header ( 'Content-Type: text/xml; charset=utf-8' ); $con = @mysql_connect ( "localhost", "root", "" ) or die ( "Couldn't connect to database" ...

drag and drop feature paired with additional textarea below

query 1: How can I make the bottom-left textarea move together with the top-left textarea when I drag it down? query 2: What is the solution to prevent the left-bottom textarea from moving when I drag down the top-right textarea? http://jsfiddle.net/4BX6 ...

Encountering a 404 error in a Next.js application while utilizing path parameters

Embarking on my journey into web development, I am trying to grasp the concept of server-side rendering using next.js and react within a lambda function. When running the code on a lambda, the result is somewhat functional as it displays the parameter valu ...

Can you suggest the best HTML5 structure for a multi-chapter novel?

In the process of creating a small HTML5 book with chapters and sections, I encountered a dilemma when it comes to structuring my documents like this: chapter1.html - introduction to chapter 1 chapter1section1.html - section 1.1 chapter1section2.ht ...