What could be causing my function to not execute when the .resize() method is

I have written a jQuery function to dynamically center my <div> element. It seems to work fine when the page loads, but fails to re-center on window resize.

Can anyone spot what I might be doing wrong?

JS:

<script>
    $( document ).ready(function() {
        function reCenter() {
            $('.content').css({
                position:'absolute',
                left: ($(window).width() 
                    - $('.content').outerWidth())/2,
                top: ($(window).height() 
                    - $('.content').outerHeight())/2
            });             
        }
        $(window).resize(reCenter());
        // To initially run the function:
        reCenter();
    });
</script>

HTML:

<div class="content">
    <h1>Header</h1>
    <span class="hyphen">-</span>
    <h2>Subtext</h2>
</div>

CSS:

* {
            padding: 0;
            margin: 0;
        }
        html { 
            background: darkgrey;
        }
        body {
            color: #fff;
            text-align: center;
            /*padding-top: 300px;*/
        }
        h1 {
            font-family: 'Arimo', sans-serif;
            text-transform: uppercase;
            font-weight: bold;
            font-size: 40px;
        }
        span.hyphen {
            color: #0CFFFC;
            font-size: 3em;
        }
h2 {
            font-family: 'Montserrat', sans-serif;
            font-weight: 100;


        }

UPDATE
Despite successfully triggering the function on page load, it doesn't behave consistently between initial load and window resizing. http://jsfiddle.net/7zqkd4w8/

Answer №1

The correct code should read $(window).resize(reCenter);. This is because you are passing the function itself, not the result of executing it.

Answer №2

In order to determine the width of the '.content' div, it is important to ensure that it is floating or absolutely positioned. By adding the absolute class to .content in reCenter(), and triggering the resize function twice during the first time, you will be able to accurately calculate the width.

$(window).on('resize',function(){
   reCenter()
}).resize().resize();

An alternative approach is to simply add 'float: left;' to the content CSS, which should allow your existing code to function correctly.

.content{
    float:left;
}

Answer №3

Here's the recommended approach:

$(window).on('resize',function(){
   reCenter()
}).resize();//activated upon initial page load

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

Manifest.json not being generated in Vue Cli 3 project for PWA

I'm currently working on a Vue Cli 3 project, and I have the @vue/cli-plugin-pwa plugin properly installed and configured in my vue.config.js file. However, when I try to run vue-cli-service build --modern, I notice that my configuration is not reflec ...

Retrieving properties of objects using HTML Select

Scenario: I encountered an issue while trying to access a specific property (code) of a ng-Model object called myRide. I initially attempted to achieve this by <select ng-model = "myRide" ng-change = "getCode(myRide.code)"> ...and within the ...

What are some techniques to ensure that my "display: grid" layout adjusts properly on mobile devices and tablets by implementing media queries?

Responsive Grid Design I am looking to transform my grid desktop view into a responsive layout for mobile and tablets using media queries in CSS. While it looks great on desktop, it does not adjust well on smaller screens. .grid-container { display: gr ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...

Troubleshooting CSS Problems in a Lightbox

I have developed a custom lightbox for watching Youtube videos that is fully functional. However, the design aspect leaves much to be desired. Please take a look at it. Despite my best efforts to improve it, the outcome is still not satisfactory. Here is ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

Seamless Integration of Full Calendar Functionality with SQL Database

I'm currently experiencing difficulty in utilizing FullCalendar's impressive jQuery calendar plugin for my application, specifically in generating events from SQL Server. Here is the code snippet: First JS $(document).ready(function() { v ...

Generating dynamic HTML elements and incorporating animated positioning

Alright, folks. I've got a bit of a tricky situation here. So, I have this file named "thedot." My PHP script reads the contents of this file and divides it into three sections, which we call dots. These dots are then displayed on the page in rows of ...

Tips on transferring large JSON data (250kb) to a MySQL database through the use of AJAX, JavaScript, and PHP

function sendProjectData(docsId, data) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { localStorage.setItem('updatedData',JSON.stringify(data)); if (this.readyState == 4 && this.sta ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

The progress indicator for AJAX file uploads is malfunctioning; the addEventListener('progress') method is not functioning as intended

For some reason, the event progress listener isn't firing in AJAX when using Chrome web browser. However, when simply using the form submit function to the form action, the file uploads as expected. Even though the file is uploading behind the scenes ...

What flaws exist in the idea of attempting to render a partial when clicking in Rails?

I am attempting to retrieve activities when the user clicks on a button labeled display in my application's interface. def display @activities = Activity.all @activities = Activity.order("created_at desc") #To fetch the Post id through ...

Users are unable to access the most recent version of the CSS file

Running a website through Hostinger has presented a unique challenge - when I make changes to the CSS file, it updates for some users but not all. It seems that the changes are being cached for certain individuals. I attempted to rectify this issue by add ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Using Jquery to create HTML elements from a C# function

I have a C# web service method that creates HTML code and returns it as a string. I want to take this HTML string from the method and replace a specific div element. function updateHTML(ID) { var gID = ID; $.ajax({ type: "get", co ...

What is the best way to implement CSS properties dynamically in real-time?

Hey there, I’m working with some HTML code here <div id="div1"></div> I’m dynamically loading content onto this div and adjusting its width in the "success" function based on the contents Here’s the jQuery code snippet I’m using Th ...

Troubleshooting Cross-Origin Resource Sharing in Three.JS and Firebase Hosting

Struggling to load a 3D model through the Three.js MT: / OBJ loader. You can see an example of what I'm trying to achieve here: The issue arises because the Three.js package requires both the files and the code to have the same base path. For insta ...

Tips for overcoming the restrictions of ASP.NET Webforms while incorporating jQuery

For anyone familiar with utilizing jQuery in .NET web applications, encountering challenges where changes made on the client side do not persist to the web server during a postback is a common issue due to factors such as viewstate and security. The situa ...

Issue with spotlight / shadow camera cutoff in Three.js

I've been grappling with a problem for hours now and could really use some help. So, I have this spotlight in my scene that I imported from a collada file, but for some reason, the shadow is getting cut off. Even when I turn on the camerashadow helpe ...

Manage shared nested modules across different modules in Vuex without redundancy

In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules. F ...