Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height();
var windowWidth = $(window).width();
var scrollTop = $(window).scrollTop();
var scrollLeft = $(window).scrollLeft();

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, ((windowHeight - $(this).outerHeight()) / 2) + scrollTop) + "px");
    this.css("left", Math.max(0, ((windowWidth - $(this).outerWidth()) / 2) + scrollLeft) + "px");
    return this;
}

$('div').center();

I attempted to position the div in the center of the page using a specific function.

However, when the window is resized or users zoom in or out, the function does not update the new position.

Is there a way to execute this function when users resize the window or zoom in or out?

Answer №1

If you're looking to achieve a specific outcome, the jQuery resize method could be the solution you need:

$(window).resize(function () {
    $('div').center();
});

Alternatively, you can accomplish this using a straightforward DOM approach:

window.onresize = function () { $('div').center(); };

Keep in mind that using the plain DOM method might override existing handlers attached to the window resize event and may not work consistently across different browsers.

It's important to ensure that these lines are within your function so they update properly when the handler is triggered:

var wH = $(window).height();
var wW = $(window).width();
var sT = $(window).scrollTop();
var sL = $(window).scrollLeft();

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

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...

Retrieval of each single row from a PHP-generated JSON dataset

This is quite challenging, especially for me. My goal here is to use Javascript to extract each value of every row in this JSON data: {"id":2,"url":"image.png","x":19,"y":10,"user_id":20} {"id":3,"url":"image.png","x":19,"y":10,"user_id":20} {"id":4,"url" ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...

Troubleshooting head.js and jQuery problems in Chrome/Firefox 5

After rendering the page, it looks something like this: <!DOCTYPE html> <html> <head> <script> head.js("js/jquery.js", "js/jquery.autocomplete.js"); </script> </head> <body> ... content ...

Dropzone failing to verify the maximum file limit

I am currently using dropzone to upload files on my website. I have limited the number of files that can be uploaded to a maximum of six. The code works perfectly when uploading one image at a time, but if I select more than six images by holding down the ...

All browsers experiencing issues with autoplay audio function

While creating an HTML page, I decided to include an audio element in the header using the code below: <audio id="audio_play"> <source src="voice/Story 2_A.m4a" type="audio/ogg" /> </audio> <img class= ...

Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse butt ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...

Transition from mouse wheel scroll to page scroll not functioning properly when overflow is enabled

The website has a fixed element that uses overflow:auto. Users can scroll this element by positioning the mouse over it. However, once the element reaches the end of its scroll, the page does not seamlessly take over the scrolling. Instead, there is about ...

Printing in ASP.Net without displaying a dialog box

Is there a way for my web application to automatically print a popup page without prompting the client to choose a printer? I am looking for guidance on implementing silent printing in ASP.Net using java-script or ajax, or any other suitable solution for ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

Leverage the router through the getServerSideProps method

My goal is to automatically redirect the user to the login page if their token has expired. I need to handle this in the getServerSideProps method where I make a request to the server for data. If the request is unauthorized, I want to use the useRouter ho ...

Transform a Mongoose object into a specific JSON schema

When retrieving data from MongoDB using mongoose as an ORM, I have a specific requirement. Instead of sending all the fetched information back to the client in the response, I need to convert the mongoose object into a JSON object that adheres to my cust ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

Preventing child element clicks in Angular 5: A helpful guide

I have checked numerous references, but unfortunately haven't received any responses. That's why I have turned to this platform in hopes of improving my code with your assistance. I need to add an element with text on click. Currently, it works ...

What is the best way to refresh a page during an ajax call while also resetting all form fields?

Each time an ajax request is made, the page should refresh without clearing all form fields upon loading Custom Form <form method='post'> <input type='text' placeholder='product'/> <input type='number&a ...

Filter the specific output in a generator function

I have a code snippet that I need help with. function* iterateRecord() { const db = yield MongoClient.connect(''); const collection = db.collection(''); const query = {} const cursor = collection.find(query); ...

how to use serializeArray() to create an array with named keys

I am struggling with a piece of HTML code : <input type="checkbox" name="search-form[filters][category][12]" value="cat-12" autocomplete="off" checked="checked" /> <input type="checkbox" name="search-form[filters][category][14]" value="cat-14" au ...