Can jQuery Alignment be Adjusted Based on the Size of the Browser Window?

After browsing through several websites, I managed to create a basic pop-up box using javascript to showcase my contact details. While I am content with its functionality, I have encountered an issue where the popup window is positioned absolutely rather than relative to the browser window. Ideally, I would like the pop up to appear at the center of the browser window regardless of the user's location on the page when they click the info icon.

Although I have a good understanding of HTML, javascript is still a bit challenging for me. I understand that relative positioning in javascript operates differently, making it hard for me to resolve this problem on my own. Any guidance or suggestions on how to address this dilemma would be greatly appreciated.

You can find the webpage here:

The script used is shown below:

<script type="text/javascript">
function toggle( div_id ) {
    var el = document.getElementById( div_id );
    if( el.style.display == 'none' ) {
        el.style.display = 'block';
    }
    else {
        el.style.display = 'none';
    }
}
function blanket_size( popUpDivVar ) {
    if( typeof window.innerWidth != 'undefined' ) {
        viewportheight = window.innerHeight;
    }
    else {
        viewportheight = document.documentElement.clientHeight;
    }
    if( ( viewportheight > document.body.parentNode.scrollHeight ) && ( viewportheight > document.body.parentNode.clientHeight ) ) {
        blanket_height = viewportheight;
    }
    else {
        if( document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight ) {
            blanket_height = document.body.parentNode.clientHeight;
        }
        else {
            blanket_height = document.body.parentNode.scrollHeight;
        }
    }
    var blanket = document.getElementById( 'blanket' );
    blanket.style.height = blanket_height + 'px';
    var popUpDiv = document.getElementById( popUpDivVar );
    popUpDiv_height = window.innerHeight / 2 - 200;
    popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos( popUpDivVar ) {
    if( typeof window.innerWidth != 'undefined' ) {
        viewportwidth = window.innerHeight;
    }
    else {
        viewportwidth = document.documentElement.clientHeight;
    }
    if( ( viewportwidth > document.body.parentNode.scrollWidth ) && ( viewportwidth > document.body.parentNode.clientWidth ) ) {
        window_width = viewportwidth;
    }
    else {
        if( document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth ) {
            window_width = document.body.parentNode.clientWidth;
        }
        else {
            window_width = document.body.parentNode.scrollWidth;
        }
    }
    var popUpDiv = document.getElementById( popUpDivVar );
    window_width = window_width / 2 - 200;
    popUpDiv.style.left = window_width + 'px';
}
function popup( windowname ) {
    blanket_size( windowname );
    window_pos( windowname );
    toggle( 'blanket' );
    toggle( windowname );
}
</script>

(I apologize for having it all in one line; Cargo Collective, the platform I use for my website, requires scripts to be formatted this way).

Answer №1

Utilize CSS position: fixed:

#my-element {
    position : fixed;
    top      : 50%;
    left     : 50%;
    margin   : -100px 0 0 -250px;
    width    : 500px;
    height   : 200px;
    z-index  : 1000;
}

Check out this demonstration: http://jsfiddle.net/huRcV/1/

This method centers a 500x200px element in the viewport. Negative margins are applied to ensure the element remains centered based on its dimensions. Even when the user scrolls, the element will remain centrally positioned within the viewport.

For more information on position, refer to the documentation here: https://developer.mozilla.org/en/CSS/position

fixed

No space is reserved for the element. It is positioned at a defined location relative to the screen's viewport and stays fixed when scrolling. When printed, it retains that fixed position on every page.

While achieving this effect with JavaScript is possible, using the CSS approach is generally recommended. If you prefer jQuery, below is a quick example:

var $myElement = $('#my-element');
$(window).on('scroll resize', function () {
    $myElement.css({
        top : ($(this).scrollTop() + ($(this).height() / 2)),
    });
});

Here is a demo showcasing this functionality with jQuery: http://jsfiddle.net/huRcV/ (note that in this demo, position: fixed has been changed to position: absolute)

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 code to incorporate a color using PHP?

Question: Is there a way to indicate approval with green color and decline with red color? I've searched for a solution but couldn't find one. PHP Code: <?php if(isset($_POST['approve'])) { $msg = "Approved"; ...

Creating jQuery tabs through looping

My goal is to create a unique tab based alphabet set using the data of employees in a database. This means that it won't be a traditional A-Z set, but will instead dynamically generate tabs based on the employees' names in the database. <cffu ...

In TypeScript, how are angle brackets like methodName<string>() utilized?

Could someone please assist me in understanding why we use angular brackets <> in typescript? For example, I have provided some code below and would appreciate an explanation. export class HomePage { constructor(public navCtrl: NavController) ...

Make sure to verify the existence of the data before trying to access it to avoid encountering an

Is there a more efficient way to handle data retrieval and avoid potential errors in React when accessing information from an API? The current code, although functional, appears to be quite repetitive. renderComicList() { var detail = this.props.ser ...

What is the best way to execute a series of AJAX functions one after the other in JavaScript?

Currently, I am working on a project that involves editing multiple elements within a window simultaneously using AJAX. My goal is to have all "open for editing" elements saved when the user clicks the save button for the entire window. However, I encount ...

Why isn't the connect.use() function working in Node.js?

I have been studying and applying examples from a book to learn Node.js. While replicating one of the examples, which involved creating a middleware, I encountered an error when trying to run the JavaScript file. The error message stated "undefined is not ...

Using only if-else statements and else-if conditions in JavaScript, arrange four numbers in order

How can I arrange 4 numbers in ascending order using only if-else and else-if statements in JavaScript without utilizing the sort function? ...

Does Javacc have a capability to generate JavaScript code as an output?

Is there a parser generator available that can take a Javacc grammar file (.jj) and produce a JavaScript parser instead of Java? If not, what would be involved in converting the .jj file into a format that ANTLR can interpret (since it has the capability ...

Preventing Vimeo from continuing to play when the modal is closed by clicking outside of it

I am facing an issue with my Vimeo video embedded in a modal. The video stops playing when I click on the 'close' button, but it continues to play in the background when I click off the modal. I have tried solutions from similar questions without ...

What is the method to define a function in express js that is accessible from all views?

Is there a way to develop a function within my Express JS MVC web application that can be accessed from any view? How can I define this function in middleware so it can be directly called from a view? I envision being able to use this function like: < ...

Effortless Sidebar Navigation for populating primary content

Initially, I must confess that even though this seems like a straightforward issue, I am just as puzzled as you are by my inability to solve it independently. With no prior experience in web development, I find myself in need of using GitHub Pages to docum ...

Executing a group query for Mongoose in a node.js/express route

Hey there, I have a query that works perfectly fine in Robomongo. Here's the code: db.av.group( { key: { roomId: 1}, cond: { dateOfDay: { $gte: new Date('12/01/2014'), $lt: new Date('12/30/2014') } }, reduce: function( curr, re ...

Is there an implicit transformation or action involved when the promise chain is resolved or rejected in $q?

Is there an intrinsic digest/apply included when the promise chain is resolved/rejected in $q? I recently switched from using $q to q in my code and it seems like a digest is no longer happening, leading to different outcomes. What could be causing this c ...

Why is the ID not being sent after a successful AJAX call using jQuery?

I'm currently utilizing JQuery to initiate an AJAX call for deleting data from a database based on ID. Here's how it's done: $(".delete").live('click', function(event) { var item = $(this), ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

Unusual activity observed in HTML5 contenteditable functionality

Within a list item, I have a span element. <ul> <li>text part 1 <span class="note">this is a note</span> text part 2 </li> <li>text part 3</li> </ul> When you double click on th ...

What could be the reason for one function returning undefined from identical API calls while the other functions produce successful results?

As I delved into incorporating the TMDB API into my project, a perplexing issue arose that has left me stumped. Despite utilizing identical code snippets in two separate files and functions, one of them returns undefined while the other functions flawlessl ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

The rotation of the Torus object in Three.js is not centered around the 0z axis

Attempting to rotate a torus along 2 axes: Ox and Oz. The goal is to apply this rotation with a slider from dat.gui that is modified by mouse input. The torus is defined as follows: var geometryTorus = new THREE.TorusGeometry( radius, 2*widthLine, 100, 1 ...

JavaScript Code to Remove an Element from an Array

I have a Javascript Filter Item Class and an array structured as follows: function FilterItem(filterId, filterType) { this.filterId = filterId; this.filterType = filterType; } var filterItemArray = []; To add Filter Items to this array, I use th ...