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

Guide on setting up a shortcut key for an input field

Currently, I have a collection of images each with its own HTML page. I added an input button that when clicked, takes you to the next image. However, I would like to enhance user experience by allowing them to use keyboard arrows for navigation. Being new ...

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

Combining ASP.NET MVC with HTML5 for dynamic web development

We are in the process of planning a new project and are interested in utilizing ASP.NET with the MVC pattern. Additionally, we want to incorporate the new features of HTML5. However, we have been having trouble finding sufficient information or connecting ...

Is there a way to replicate the Vista Command Link in HTML?

This particular dialog mimics the design of a Windows Vista Command Link: View image here: http://i.msdn.microsoft.com/Aa511455.commandlinks01(en-us,MSDN.10).png I'm curious if anyone has created HTML code that replicates the appearance and function ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

css background is repeating after the height of the div is reset

I'm working on a project where I want to resize an image while maintaining its aspect ratio to fit the height/width of the browser window. However, every time the code for resizing is implemented, the div height continues to increase with each resize ...

Talwind Flexbox Grid Design

Currently, I am exploring the world of website layout creation using Tailwind Flexbox Grids as I believe it can add significant value. However, I have encountered some queries: How does one go about constructing a layout like this? Referencing this speci ...

Troubleshooting Problem with CSS Display in Spring Security 3.2

After deciding to integrate 'Spring security 3.2.0' into my current web application, which was originally developed without Spring and utilizes Primefaces & EJB 3, I encountered a challenge. Upon starting the basic configurations, I noticed that ...

Type content in HTML5

Can you help me with a simple question? I am currently working on building my portfolio using html https://i.stack.imgur.com/rxYRS.png I want to be able to click on an image and add the description of my choice. Right now, it is showing something else: ...

What is the best way to fetch d3 data from a service?

I've been exploring a tutorial on creating charts with d3, which can be found at: When it comes to loading data for use in d3, I typically rely on the following code snippet: d3.tsv("data.tsv", type, function(error, data) { The file "data.tsv" is c ...

Visualizing Data with HTML and CSS Chart Designs

I'm seeking assistance with creating an organization tree in a specific layout. I am having trouble replicating the tree structure shown in the image. I need help generating a similar tree structure where multiple levels are displayed, including ext ...

In the Bootstrap multiselect feature, users will be able to choose whether to display an image or selected text

Is there any way to display an image by default instead of options? Code: <select id="example-post" style="width:120px;!important;" class="footerSelect" name="multiselect[]" multiple="multiple"> <opti ...

Modify the CSS class by adding attributes dynamically instead of directly to the element

I encountered a situation where I needed to apply a css property to a class rather than an element. For example: $('.class_with_css').css({display:'none'}); This code would add the style "display:none" to all elements with the cl ...

Prevent scrolling on both md-sidenav and md-content in AngularJS Material

Currently, I am working on a website using AngularJs Material sidenav. My goal is to make both md-sidenav and md-content appear as one page, without any scroll bars showing up when the height of one element exceeds that of the other. How can I achieve th ...

Obtaining JSON values by key name using JQuery

I am trying to extract JSON data using an HTML attribute How can I retrieve JSON values based on the translate attribute and "ed" key? JSON FILE { "open" : [ { "en": "Open", "ed": "Opened ...

hover effect malfunctioning

I have created a maze but am having trouble with the hover effect not working. Any help would be greatly appreciated. $('.wall') .bind('mouseenter', function() { $(this).css({ 'background-color': 'green' ...

Instant access to an interactive online platform

Is it feasible to create a shortcut from a webpage to my desktop for quick access? For instance, if a dynamic web page has 15 documents and I want to easily create shortcuts to them on my desktop by clicking on each one. I understand this is a brief quest ...

Adjusting the Pace of a CSS Marquee

My CSS marquee effect is working perfectly, but I am having trouble with the speed. The issue arises when the text length varies - shorter text takes longer to scroll while longer text scrolls quickly. This inconsistency is due to the animation duration an ...

Efficiently convert a JSON array into an HTML table using the Jquery

Currently, I'm facing a challenge in my project. The issue arises when a query is sent to the server using jQuery, and an array is returned as a response. My struggle lies in transferring this data to a dynamic table since the column count varies with ...

Hide the div if the content is empty

Within a div created by the_content, there may be content or it could be null, resulting in an empty div that I want to hide. To address this issue, I attempted to store the content in variable $pageContent. However, upon declaring the variable, it either ...