Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its original position in the list.

I know that by changing the position property from 'unset' to 'relative', I can give the card movement functionality using properties like 'left' and 'top'. But, I need a solution that will automatically center the selected card regardless of its initial position on the screen.

Is there anyone out there who knows how to achieve this using JavaScript?

My intuition tells me that it should be possible to retrieve the current location of the node and then move it to the center of the screen, but I'm not certain about the exact steps needed to make this happen...

For better understanding, here is an image showcasing the situation: CardsProject

UPDATE: As a temporary solution, I have decided to set an absolute position for the card. This method, however, eliminates any CSS transition effect from the card's original position to the center of the screen, causing the card to temporarily lose its place within the deck.

Image before click: click here for image

Image after click: click here for image

Answer №1

After tirelessly searching the depths of the internet and debugging my code, I finally stumbled upon the solution.

The key revelation: Avoid using 'relative' positioning!

Instead, a better alternative is to maintain the element's original position while allowing it to move freely with CSS properties like top or left, achieved through the magic of position:sticky;!

By utilizing this approach in conjunction with JavaScript's coordinates documentation, specifically getBoundingClientRect(),

    .getBoundingClientRect()

...I successfully cracked the enigma. The function I devised to calculate a vector between the current object and the center of the screen can be accessed below, yielding X and Y vectors in an array format.

  function calcCenterMove(element){

    /*
    Variables such as X and Y represent the current position of the element (top left corner).
    Width and Height denote the dimensions of the element.
    CX and CY indicate the X and Y coordinates of the screen's center.
    */

    var x       = element.getBoundingClientRect().x;
    var y       = element.getBoundingClientRect().y;
    var width   = element.getBoundingClientRect().width;
    var height  = element.getBoundingClientRect().height;
    var cx      = window.innerWidth / 2;
    var cy      = window.innerHeight / 2;
    var xVector = cx-(width/2)-x;
    var yVector = cy-(height/2)-y;
    return [xVector, yVector];
  }
  var xAxisMove = calcCenterMove(element)[0];
  var yAxisMove = calcCenterMove(element)[1];
  element.style =   "transform: translate("+xAxisMove+"px,"+yAxisMove+"px);";

To elevate the element visually above others, I assigned a z-index value and incorporated a dimming overlay on the screen to restrict user interactions elsewhere.

Issues may surface when resizing the browser window, which warrants separate attention; one potential avenue involves employing an event listener to recalibrate the element's center based on screen adjustments using the same cx and cy parameters outlined earlier (or possibly the entire function).

Nonetheless, the sought-after resolution has been attained, open for utilization by those who may find it beneficial!

For visual aides, refer to the images below:

Initial State

Final Position

Best wishes!

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

What is the best way to update a deeply nested array of objects?

I have an array of objects with nested data that includes product, task, instrument details, and assets. I am attempting to locate a specific instrument by supplier ID and modify its asset values based on a given number. const data = [ { // Data for ...

Is it a bug that using addClass or toggleClass with JQuery inside a click method does not seem to be functioning properly?

This appears to be a simple issue, yet it is not functioning correctly. I managed to make it work by placing the .normal class above the .highlight class, despite only adjusting the position and not altering the style. This lack of logic is puzzling. Sin ...

How can I identify when a CSS transition on a particular element has ended if there are several transitions occurring simultaneously?

In my coding, I have been utilizing the following method to identify when a CSS3 transition has finished: CACHE.previewControlWrap.css({ 'bottom':'-217px' }).one('webkitTransitionEnd transitionend m ...

Identify any fresh elements incorporated into the DOM following an AJAX call

I'm attempting to showcase a newly added div element within the DOM using AJAX. Through AJAX/PHP, I dynamically inserted some new buttons: <button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index ...

My divs seem to overlap in strange, unpredictable ways depending on the zoom level - it's an odd phenomenon that occurs

This situation is causing me frustration... depending on the zoom level of the browser, my boxes do not align properly and it ends up looking messy (in all browsers). Any advice? Could I handle this more effectively with jQuery? HTML </div> <div ...

Navigating Modal Pop-ups in Django

My current approach for handling modal windows involves referring to this article here. However, I am struggling with implementing some basic functionality using this method. Within my HTML code, I have the following structure: {% for order in queryset% ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

"Exploring the process of retrieving data from a request in Node.js with the help of the Express

I'm encountering some issues with integrating a "login" form into my Node.js script. While I can get it to work using a static HTML page, utilizing a dynamic ".ejs" page is causing trouble as my form fields are showing up as "undefined". var helmet = ...

Choosing dynamically created components:Making a choice among elements that are generated

Currently, I am working on a task that involves moving list items between two separate lists and then returning them back upon a click event trigger. Below is a snippet of the basic HTML structure: Unchosen: <br> <ul id="unchosen"></ul> ...

Python Automation with Selenium Web Scraping

I attempted to scrape the content of Crédit Suisse's page as an exercise. After creating this script, I encountered difficulties in retrieving the data. Initially, I suspected it may be due to an iframe issue or an AngularJS website structure, but u ...

Encountered a header error while attempting to proceed with the

In one of my routes, the following code is implemented: if (elements.length <= 0) { var msg = 'no elements found'; console.error(msg); var err = new Error('Not found'); ...

Following my ajax submission, the functionality of my bootstrap drop-down menu seems to have been compromised

I'm having an issue with my login page. After implementing Ajax code for the reset password feature, the dropdown menu on the login page doesn't work properly when wrong details are entered and the page reloads. I've tried using the $(' ...

Utilizing Jquery to interchange two values and update styling

I am looking to create a script that allows me to select a black div by clicking on it (turning it red), and then transfer the value from the black div into a white div with another click. The functionality works as expected when swapping values between tw ...

Error: The strategy for authentication is not recognized as "login" - Express and Passport

I am currently experimenting with a basic MEAN stack tutorial I found online. The technologies involved are: Node.js Express.js Passport.js Below is the code snippet for the application file: app.js var express = require("express"); var mongoose = req ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

Tips for validating date input in a TextBox using JQuery on an ASP.NET platform:

Here is some code I wrote: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="datetime.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <tit ...

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...