Position a dynamically generated cell in the middle of the window

I am currently developing an employee directory that allows users to search for a specific employee and view their information in a tree or org-chart layout. To achieve this, I have implemented the Google Org Chart code for generating the chart. Each employee's contact card is displayed within a <td>, with managers and subordinates arranged above or below in separate <tr> elements.

https://i.sstatic.net/DZCed.png

While scrolling horizontally to view a small number of subordinates is not an issue, it becomes cumbersome when there are more than 10 employees as the searched employee may be out of sight:

https://i.sstatic.net/PKN9c.png

This situation can be frustrating for users. I attempted to solve this by placing an anchor (<a name="anchor">) within the card and jumping to it on page load. However, this only partially scrolls the page, making it less effective.

My goal is to have the employee's card centered on the screen so that it grabs immediate attention from the user.

Is there a method to directly jump to the searched employee when the page loads?

If needed, here is a sample code snippet representing an individual card:

<td>
    <h1>Mike</h1>
    <div class="cardBody">
        <img src="Images/stock1.jpg" style="float:left; margin-right:5px;" /> 
        <table class="data" cellpadding="0">
            <tr>
                <td><i class="fa fa-briefcase"></i></td>
                <td><span style="color:red;">President</span></td>
            </tr>
            <tr>
                <td><i class="fa fa-building"></i></td>
                <td>Administration</td>
            </tr>
            <tr>
                <td><i class="fa fa-globe"></i></td>
                <td>Home Office</td>
            </tr>
            <tr>
                <td><i class="fa fa-phone"></i></td>
                <td>Ext. 2402</td>
            </tr>
            <tr>
                <td><i class="fa fa-envelope"></i></td>
                <td><a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b636f67624e6f6a6a7c6b7d7d206d6163">[email protected]</a>">Send Email</a></td>
            </tr>
        </table>
    </div>
</td>

Answer №1

I'm a bit puzzled by what you have attempted so far. Are you able to use jQuery? If yes, you may find this solution straightforward.

$(container).scrollTo(target);

If you can pass your "target" through a URL query, then you should be able to parse and utilize it as shown below:

Note: This assumes you have a URL like www.website/searchpage.html?i=targetID

Also: This is set up to work with IDs, so adjust the code if you need it to work with classes.

var params;    
function parseURLParams(url) {
        var queryStart = url.indexOf("?") + 1,
            queryEnd = url.indexOf("#") + 1 || url.length + 1,
            query = url.slice(queryStart, queryEnd - 1),
            pairs = query.replace(/\+/g, " ").split("&"),
            parms = {}, i, n, v, nv;
    
        if (query === url || query === "") {
            return;
        }
    
        for (i = 0; i < pairs.length; i++) {
            nv = pairs[i].split("=");
            n = decodeURIComponent(nv[0]);
            v = decodeURIComponent(nv[1]);
    
            if (!parms.hasOwnProperty(n)) {
                parms[n] = [];
            }
    
            parms[n].push(nv.length === 2 ? v : null);
        }
        return parms;
    }

$(document).ready(function(){
   params = parseURLParams(window.location.href);
   $("#Container").scrollTo("#"+params.i);
});

I hope this explanation benefits someone.

Edit: I understand that you want it to be centered, which could be a bit tricky. Your container would need to be significantly larger (or maybe infinite?) than necessary to accommodate all the data. Then, scroll to the position of the desired element, plus an offset for half of the container's visible width and half of the element's width. You might consider creating an invisible element with absolute positioning when calculating this number. Move the element to this position and ultimately the screen to this element.

Answer №2

To direct the URL to a specific div ID, you can simply append it to the end of the URL. For instance, in the code snippet for the card you provided, you would modify the div as follows:

<div class="cardSection" id="saraCard">

Next, update the link to point to this section on the page:

<a href="employees.html#saraCard">Link to Sara's card</a>

Alternatively, if you want to create an internal link on the same page:

<a href="#saraCard">Go to Sara's card</a>

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 use multiple encoding types when sending data via a POST method in Node.js?

My current challenge involves sending a combination of name and description text data alongside a video file. Unfortunately, I've encountered an issue where I can only send either the video or the text, but not both simultaneously. Below is the code ...

Are you in need of an IDE for Javascript, CSS, HTML, or Java

Alright, time to make a decision. I'm torn between Aptana, Eclipse, and Netbeans. Ideally, I want a versatile program that can handle all the different languages I plan on experimenting with - HTML, CSS, Javascript, and Java. I already have Visual Stu ...

Encountering difficulties resolving the dependency tree while trying to install @react-navigation/[email protected]

After creating a new project called MyProject using react-native init MyProject, I opened it in VSCode and the first task was to install navigation. Initially, when running npm install @react-navigation/native @react-navigation/stack, it threw an error. S ...

delete content of file in vue 3

I have a Vue 3 component that looks like this: <template> <input type="file" :class="inputClass" accept=".pdf" @input="onFileSelect" ref="fileInput"> </template> <script> import ...

The use of Physijs and implementing setLinearVelocity for object movement

2-09-2015 - UPDATE: The code provided below is now functional with the use of setLinearVelocity(). If you were facing similar issues, this updated code may help you. Find the original question with the corrected code below... A player object has been deve ...

Use a post request with the deleteOne function to remove an entry from a MongoDB collection

Currently enrolled in a Nodejs course and diligently following the instructor's steps. I've replicated the exact code shown by the instructor, but upon execution, encountered this error message: Cannot read property 'id' of undefine ...

The website's content is displayed as a mobile-friendly menu

I've been working on creating a responsive menu using HTML and CSS, and everything is functioning well so far. However, I'm facing an issue with the mobile view of the menu. When the menu opens up, it obstructs the text below it, making it diffic ...

Resize Font Awesome icons dynamically based on screen size changes

Currently working on creating a footer that includes social media icons from Font Awesome. However, I've come across an issue where resizing the desktop size for tablet or mobile screens causes the icons to shrink, which is not ideal. If anyone has a ...

KnockoutJS is not recognizing containerless if binding functionality

I was recently faced with the task of displaying a specific property only if it is defined. If the property is not defined, I needed to show a DIV element containing some instructions. Despite my efforts using $root and the bind property, I couldn't ...

Tips on playing HTML video only when it is in the user's view

Currently, I am working on a TikTok-inspired UI project. However, I am facing an issue where videos do not autoplay when they come into view after scrolling, similar to how it works on TikTok. Here is a demo for reference. Below is a snippet of my code: ...

Resizable table example: Columns cannot be resized in fixed-data-table

I've implemented a feature similar to the Facebook example found here: https://facebook.github.io/fixed-data-table/example-resize.html You can find my source code (using the "old" style with React.createClass) here: https://github.com/facebook/fixed- ...

Working with the Response Object in Django/JQuery and passing it to javascript using Urllib3

I am facing a challenge in downloading headlines from BBC using Ajax and jQuery in Django. I am attempting to use Urllib3 to create a request for the RSS/XML Top News data from the BBC website available at this link: '' Although I believe I hav ...

JQuery Datatables: Struggling to make JQuery function work following AJAX update

Watch this screencast to get a clearer understanding of the issue.... I'm currently working on my first project involving AJAX, and I'm encountering some obstacles. The datatable is loading user details from a JSON output using AJAX. Each row ...

Experiencing difficulties in displaying a React element that is being passed as a prop

One of my components looks like this: const Chip = (props) => { const ChipIcon = props.icon; let deleteButton = null; if (!props.readOnly) { deleteButton = <Delete style={styles.deleteButton} onTouchTap={props.onRemove} /& ...

Feeling overwhelmed by JavaScript promises while working with forEach loops

Let's imagine a scenario where we have a dictionary that keeps track of scores for different types, such as {a:0, b:0, c:0}. I have three MongoDB collections - A, B, and C. First, I query collection A using: A.find({<key>:<value>}) .then( ...

Organizing JSON objects into groups of x items

I am working with dynamically generated JSON data that needs to be grouped by a specific number. I have a method for generating the variable representing the grouping number, but now I need to organize the items based on that number. Here is the original J ...

Verify whether the headers in the CSV file correspond; if they do, proceed with parsing, otherwise halt

I am currently working on implementing validation for a specific .CSV format before proceeding with parsing using PapaParse. My plan is to first check the headers and verify if they match the following: Extension, company, name If the headers match, the ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

What is the most efficient method for generating random dark colors using javascript code?

Looking for a function that specifically returns dark colors. Although I can generate random colors with the code below, how do I make sure it only retrieves dark ones? document.getElementById('mydiv').style.backgroundColor = '#' ...

Ensure that you specify the scalar variable @TextBox1 in ASP.NET before proceeding

Here is a snippet of code that I am sharing for the solution to my latest application. Upon executing this code, an exception is thrown stating "Must declare the scalar variable @textBox1". public partial class About : Page { SqlCommand cmd = ...