When resizing the browser window, this single horizontal page website does not re-center

I am in the process of creating my very first one-page horizontal website using jQuery and the scrollTo plugin. This site consists of 3 screens and initially starts in the center (displaying the middle screen). To achieve this, I decided to set the width of the <body> element to 300%, with each screen having a width of 33.3333%. When a user clicks on a link (<a>), jQuery smoothly transitions them to another screen by moving left or right.

While this functionality works perfectly, I encounter issues when resizing the window as the layout loses its structure and the widths no longer align properly. I am seeking guidance on how to rectify this issue and more importantly, understanding why it occurs in the first place.

You can view the source code here: Mr. Fiddle. Feel free to resize your window to see the problem for yourself. Thank you!

Answer №1

After considering your feedback in one of the comments on Luke's answer, I revisited this issue about needing to keep track of your previous location.

In order to ensure you can return to where you were after resizing, you can implement a similar code structure like this:

var lastPosition = "middle";
var $body = $('html, body');

window.scrollTo(($(document).width() - $(window).width()) / 2, 0);

$('#go_left').click(function() {
    $body.scrollTo('0px', 800);
    lastPosition = "left";
});
$('#go_right').click(function() {
    $body.scrollTo('100%', 800);
    lastPosition = "right";
});
$('#left_link').click(function() {
    $body.scrollTo('50%', 800);
    lastPosition = "middle";
});
$('#right_link').click(function() {
    $('html, body').scrollTo('50%', 800);
    lastPosition = "middle";
});

$(window).off('resize.menu').on('resize.menu', function() {    
    switch(lastPosition)
    {
        case "left":
            $body.scrollTo('0px', 0);
            break;
        case "middle":
            $body.scrollTo('50%', 0);
            break;
        case "right":
            $body.scrollTo('100%', 0);
            break;
    }
})​

Check out the DEMO for a visual representation.

I've optimized by caching the body element to improve performance slightly.

Remember to unbind the event when leaving the page to prevent memory leaks.

While there is still some lag in re-positioning, I'm working on resolving that next.

Edit
I found a way to reduce lag and flickering during resize events.

Using scrollLeft() instead in the resize method yields better results, although not perfect it is a significant improvement:

$(window).off('resize.menu').on('resize.menu', function() {   
    var elementToScrollTo = "div#main";

    switch(lastPosition)
    {
        case "left":
            elementToScrollTo = "div#left";
            break;
        case "middle":
            elementToScrollTo = "div#main";
            break;
       case "right":
            elementToScrollTo = "div#right";
            break;
    }

     $(window).scrollLeft($(elementToScrollTo).position().left);
})

View the updated DEMO with improved functionality.

Answer №2

When utilizing the scrollTo plugin, consider using a DOM element (specifically, a child of the scrollable element) as the target for scrolling.

$('html, body').scrollTo($('div#right'), 800);

Answer №3

$(window).resize(function() {
    $('html, body').scrollTo('50%', 0);
});

This solution could potentially be more efficient than the previous one mentioned by Francois, as it eliminates the need to constantly recalculate widths. Instead, this code will be triggered each time the window size changes by even just a single pixel.

Answer №4

Include the following script to center a webpage horizontally when resizing the window:

http://jsfiddle.net/EAzS9/1/

$(window).resize( function () {
    window.scrollTo(($(document).width() - $(window).width()) / 2, 0);
});
​

Answer №5

When utilizing the scrollTo function, inputting a percentage value actually results in an absolute pixel value being set. Adjusting the window size will not alter this absolute pixel value unless you include an event handler for the "resize" event to recalibrate the scroll value. It may be more effective to work with absolute pixel values when dealing with such scenarios. Set the width of each .page div in pixels and enclose them in a div with a significantly large width to ensure compatibility with future pages. Instead of scrolling, adjust the left offset of the wrapper element. The original coda slider utilized this approach, and it is likely that the current version continues to do so.

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

Show a 1920x1170 / 183KB image as the background using CSS styling

I need help with displaying a background image that is 1920x1170 pixels and has a file size of 183KB. Here is the code I am using: .bground{ height:auto; left:0; position:fixed; top:0; width:100%; } <div class="bgrou ...

How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

Tips for inserting PHP information into the <link rel="stylesheet" type="text/css" href="CSS/sheet.css" /> reference tag

In my script, I have successfully implemented a feature that displays the OS and browser details. The output is in the form of eight CSS scripts, showcasing Mac, PC, and Ubuntu OS's with IE, Firefox, Safari, and Chrome browsers. While the script is st ...

How can I extract the "href" attribute from an anchor tag using XPath?

I am working with HTML code that looks like this: <a href="/images/big_1.jpg" class="class-a"> <img class="class-img" src="/images/small_1.jpg"/> <span class="class-span"> <img src="/images/img_1.png"> </ ...

Steps to obtain an Element binding from a Svelte component

Is it possible to retrieve the bounding client rect of an anchor element? I typically mark this using the syntax bind:this={someVariable}. However, when I add this code to a Svelte component, I receive a different object that Svelte uses to represent a c ...

Conceal the background of the lower div when the top div is displayed

I am struggling to figure out how to achieve this, or if it can even be done: <body> has a background image <div parent> has a background image <div child></div> does not have a background </div> My goal is to make the chi ...

Skillful management of JQuery Ajax JSON errors

I have developed an Ajax save function for storing employee data, which returns a JSON object containing the details of the save operation. These details are then displayed on the browser. However, there are times when my server-side code may generate PHP ...

Is specificity a characteristic of JavaScript?

After setting a div in my HTML file to have a height of 100px and a width of 100px, I attempted to retrieve the height using JavaScript. This is what I tried: console.log(document.GetElementById("box").style.height); // The div had an ID of "box" and w ...

The value of the file input is not appearing once the form has been submitted

After submitting my form, I am able to get the values of input[type='text'] and input[type='reset'], but not of input[type='file']. My form submission involves AJAX with jQuery and PHP. Can anyone provide a solution? I have a ...

Exploring color options in matplotlib for HTML designs

Is there a way to change color in a matplotlib plot using html in Python? I attempted plt.plot(x,y,marker=".",color="#e0e0e0") However, this resulted in data points displayed as ".", connected by lines of color #e0e0e0 which is not desired. I also experi ...

Locate the source attribute of an image using JQuery

How can I use JQuery to extract the img src link? <tbody> <tr> <td headers="header_0 header_1">&#160;<img src="https://this-link-here.com" width="26" height="24" ...

Asking for an array of PHP objects using jQuery Ajax: a guide

I'm facing a challenge with passing an array of "Blocks" using Ajax. I have successfully created the "Blocks" using a PHP class and know how to pass an array with numbers through JSON, but I am unsure how to pass an array with objects. Do I need to c ...

The Ajax Form disappears from the page

After racking my brain for a while, I've come to the conclusion that it's time to seek some assistance. I have work tomorrow and I don't want to spend all night on this. The issue lies in my form which is located inside a modal, here is my ...

Exploring the power of internal linking with GatsbyJS

I am currently developing a website using gatsbyjs. I have concerns about the crawlability of "onClick" for SEO purposes and I would appreciate some assistance. This is my current code: render={data => ( <div className='feed'> ...

Display HTML containing a <script> tag within a REACT component

Looking to embed the following HTML code within a React component: <form action="/process-payment" method="POST"> <script src="https://www.example.com/payment-script.js" data-preference-id="$$id$$"> </script> </form> I ...

New update: Adjusting the chart by using the slider to modify the date values on the x-axis

Update: I have made changes to the question, the issue with values not appearing on the x-axis has been resolved. Now, as the slider is moved, the data on the graph remains constant and I can see changing x values. I am currently working on incorporating ...

Tips on Incorporating CSS in import.io Connect Extract

By utilizing the import.io connector, I successfully extracted a portion of HTML from the source website. The output was returned as "html" type, consisting of a single table of data with styles defined in the body HTML but not fully extracted. Consequentl ...

Is there a way to insert a value into the input field using JQuery or JavaScript?

After reading my previous post on posting values into an input box, a commenter suggested using JQuery or Javascript. For more code and information, please refer to the link provided above. <label>Date</label>:&nbsp&nbsp <input sty ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

When clicking, populate the content of another div in a vertical top-to-bottom fashion

I am in the process of creating a functionality where clicking on one element will fill another element's content from bottom to top. Although I have managed to make it work on hover, the same functionality is not triggered when clicking on the eleme ...