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

CSS3 transition not functioning as expected

I am attempting to use CSS3 transition effects to change the background and text color when hovering over a button. However, only the text color is changing and not the background color. You can view my code on jsfiddle here. Here is the CSS I am using: ...

.then function not functioning properly in Axios DELETE request in a React project

I am currently facing an issue with calling a function to update the array of notes after deleting a note from the database. The function causing the error is called deleteNote, and the function I intend to call within the .then promise is getNotes. Here i ...

Using jQuery to remove the 'active class' when the mouse is not hovering

I recently came across this amazing jQuery plugin for creating slide-out and drawer effects: However, I encountered a problem. I want to automatically close the active 'drawer' when the mouse is not hovering over any element. The jQuery plugin c ...

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

Looking to recreate this style of table using HTML and CSS?

Trying to replicate the layout from this image for my blog, but struggling with the source code. Any suggestions on how to achieve a similar design without using divs within table rows? Looking for a cleaner solution. ...

Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields. Here is the HTML code for the form: <form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader"&g ...

Commitment of service within AngularJS controller using the "as" syntax

I'm experiencing an issue with the code snippet below. I prefer using the controller as syntax and assigning data to 'this' instead of $scope. The problem is that in this scenario, when using $scope.user everything works fine, but when tryin ...

Why aren't the divs appearing on the page?

I have developed a JavaScript and PHP page where the script in the PHP page sends data to my SQL database. However, the result is not displayed on my home page. Here is the code snippet: function getVote(question_ID) { var option_ID = document.queryS ...

What's the best way to arrange my containers for optimal placement?

I'm attempting to create a Thymeleaf template for rendering a printable PDF. Here is what I currently have: <html xmlns:th="http://www.thymeleaf.org" > <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

Using ReactJS to search for and replace strings within an array

A feature of my tool enables users to input a string into a textfield and then checks if any words in the input match with a predetermined array. If the user's string contains a specific name from the array, I aim to replace it with a hyperlink. I&a ...

"Exploring the Dynamic Display of Ajax with HTML5 Canvas

This is my first time exploring the world of ajax, and I'm finding it quite challenging to grasp the concept and functionality. What I aim to achieve: I envision a scenario where I can freely draw on a canvas and simply hit save. Upon saving, the da ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

Could data be transmitted from the server to the client without appearing in network traffic?

I'm in the process of creating a drag-and-drop text game where players have to match correct pairs. Once they've matched all the pairs, they click a button to see how many they got right and wrong. The score is recorded, the boxes reset with new ...

Issues with cascading style sheet navigation designs

Working on this project is new to me and I am encountering a challenge with two issues. My goal is to create a menu display similar to the image shown here: The problem lies in my inability to underline the selected option and make the menu display horiz ...

The Formik Material UI Localization Provider is not functioning properly when paired with the Luxon Adapter for formatting dates in

Currently, I am utilizing the MUI localization provider in conjunction with the luxon adapter to transform the date format to GB. However, despite my efforts, the date remains in the mm/dd/yyyy format rather than displaying as dd/mm/yyyy. Please refer ...

Identifying the presence of a mouse inside an element using jQuery

I am working on a website that utilizes jQuery. The structure of my page is as follows: <div id="page"> <!-- Content goes here --> <div id="content"> <div class="row"> <div class="col"><!-- content goes here ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

Displaying selected checkbox values in a URL with parameters using PHP and JavaScript

I am looking to extract the selected checkbox value and append it to the browser URL with a parameter name. Below is my HTML code: <div style="width:200px; float:left"> Price <div> <input type="checkbox" name="price" value="0-1 ...