What is the best way to make an element fixed vertically in a mobile browser while also enabling horizontal scrolling?

When using a Desktop browser, I have found a javascript code that allows me to vertically fix an element while still enabling horizontal scrolling. The element is repositioned with each scroll event. You can test this out by trying both horizontal and vertical scrolling in this JSFiddle.

var verticallyFixedBox = document.getElementById('verticallyFixedBox');

window.addEventListener('scroll', function() {
    verticallyFixedBox.style.top = '' + document.body.scrollTop + 'px';
});

Unfortunately, this method does not work well for mobile browsers. Mobile browsers do not refresh their display until after the drag is complete, resulting in a choppy user experience.

Is there a better approach to vertically fixing an element while still allowing for horizontal scrolling on mobile browsers?

Answer №1

To achieve a fixed header with a scrollable content box, you can utilize a container box with a height set to 100%. By also setting the height of the html and body elements to 100%, you can then use position: absolute; top: 0; for the fixed header. Additionally, set overflow: auto (or scroll) for the vertical scrolling box.

Make sure to reset the margins of your body and html to 0 to prevent any default browser styles from interfering with the layout.

I have made adjustments to the original fiddle you provided: http://jsfiddle.net/jb489ddL/1/

This solution does not rely on JavaScript, making it suitable for mobile browsers as it does not depend on the scroll event.

Answer №2

You have the ability to achieve this using only CSS.

#verticallyFixedBox {
  position: sticky;
  top: 0;
}

body {
  margin: 0;
}
#verticallyFixedBox {
  position: sticky;
  top: 0;
  background: #ccc;
  border-bottom: 2px solid #000;
  padding: 10px;
  white-space: nowrap;
}
<div id='verticallyFixedBox'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed ipsum nec sapien fermentum luctus. Fusce varius arcu ut nibh efficitur, quis euismod elit lobortis. Cras at fringilla lectus. Proin ac vulputate metus. Fusce eu mattis urna, at cursus elit. Aliquam erat volutpat. Ut tincidunt et...urna vel, ultrices ante.
</div>
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed ipsum nec sapien fermentum luctus. Fusce varius arcu ut nibh efficitur, quis euismod elit lobortis. Cras at fringilla lectus. Proin ac vulputate metus. Fusce eu mattis urna, at cursus elit. Aliquam erat volutpat. U...
</p>
<p>
  Nunc non turpis non orci consectetur bibendum eget vitae urna. Nulla dictum, orci sit amet luctus consectetur, nisi nisl rutrum sapien, ut fermentum urna dui a ipsum. Mauris commodo convallis mi, sed ullamcorper enim mollis eget. Maecenas risus felis, lobortis eu interdum elem...
</p>
<p>
  Etiam placerat lorem non sem feugiat, non tristique neque maximus. Maecenas ultrices scelerisque ante, ut bibendum nunc tincidunt maximus. Proin placerat tincidunt quam in scelerisque. Sed nunc tortor, ultricies ut tincidunt eu, molestie id nunc. Nam nisl mauris, scelerisque at ph...
</p>
<p>
  Nullam gravida, est ac gravida vulputate, nibh quam bibendum nisl, et posuere eros enim ac ante. Nullam eu tortor vel dui aliquam mattis non a mi. Sed porttitor sem id purus efficitur, at maximus nisi placerat. Integer imperdiet quam a risus varius, feugiat commodo diam dictum....
</p>
<p>
  Mauris fermentum eros quis metus tempor venenatis. Suspendisse est nisl, finibus sit amet malesuada vel, pharetra eget neque. Curabitur malesuada non nibh eu pellentesque. Aenean ultrices ante sed lorem rhoncus, ac volutpat urna condimentum. Mauris tincidunt mauris et pretium pe...
</p>

Please be aware that not all browsers currently support sticky positioning.

Answer №3

For resolving a layout issue, it is best to avoid using JavaScript. The objective appears to be keeping the top-most element, verticallyFixedBox, stationary while allowing its contents to scroll regardless of screen size.

To achieve this, move the content of verticallyFixedBox into a separate div element. This child div should be designated as the scrollable area. Ensure that you fix the top, left, and right sides of verticallyFixedBox to the corresponding sides of the browser window.

#verticallyFixedBox
    background: #ccc;
    border-bottom: 2px solid #000;
    padding: 10px;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

#scroll {
    position: relative;
    overflow: scroll;
    white-space: nowrap;
}

<div id='verticallyFixedBox'>
    <div id='scroll'>
    Lorem ipsum dolor...rest of text. 
    </div>
</div>

By fixing the outer container and enabling scrolling within it, you can achieve consistent display on various devices. Check out the updated version on your JSFiddle. Hopefully, this solution aligns with your requirements.

Additionally, I have provided a link to a sample page showcasing the code in an unlinked folder on my server: Test Page. It seems to work well on my mobile device.

Answer №4

When you utilize position:fixed; in your design, JavaScript is necessary but only for incorporating horizontal scrolling functionality.

To achieve this, I made adjustments to my fiddle so that it now supports horizontal scrolling as well.

The approach I took involved maintaining the verticalFixedBox with position:fixed in its designated spot while introducing another div containing the same content but with an opacity of 0.01 and positioned absolutely to facilitate horizontal scrolling.

View the example here: http://jsfiddle.net/8jzhtg9w/7/

For the HTML structure:

<div id='verticallyFixedBox'>
    <!-- Content goes here -->
</div> 
...
<!-- Other content elements -->
...
<p>
    <!-- More content here -->
</p>

In terms of CSS styling:

#verticallyFixedBox {
    /* Styling properties */
}
.scroller {
    /* Additional styles for horizontal scrolling */
}
#padder {
    height: 30px;
}

And the JavaScript snippet to handle the scrolling effect:

$(window).scroll(function() {
$('#verticallyFixedBox').css({
        'left': -1 * $(this).scrollLeft()
    });
});

Note that there may be a compatibility issue with opera-mini not fully supporting the position:fixed feature yet: http://caniuse.com/#feat=css-fixed

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

Is It Possible to Create Flash Content Without Using a SWF File?

Is there a way to embed Flash directly in HTML, rather than linking to an external SWF file? I am looking to send an HTML form via email for the recipient to fill out by opening it in a browser. The final step would involve copying the result to their clip ...

I am receiving a reference error even though the day variable has already been defined. Can you kindly point out

When I attempt to log in, the page is giving me the correct output. Interestingly, even after encountering an error, the webpage continues to function properly. app.get("/", function(req, res) { let day = date.getDate(); console.log(day); r ...

Retrieve JSON data from an external link and showcase it within a div, unfortunately encountering an issue with the functionality

Encountering the error message "XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access" Check out the plunker link for more information: http ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

Effective and Sustainable Methods for Error Management in Node/Express API Endpoints

Throughout my experience with developing MEAN Stack applications and setting up APIs, I have encountered some uncertainty when it comes to handling errors within API Routes. If there are any inaccuracies in my explanation or if my concepts are flawed, ple ...

Issue with an Angular filter for formatting a lengthy JSON string onto separate lines within an HTML document

Just starting out with coding and working in Angular, I'm trying to display JSON data from Firebase in HTML. Here's the specific call I'm using: <p>{{workout[0].box.info.training.strength.exercise[1].movement.freetext }}</p> Th ...

Extra assistance might be required to manage the output from these loaders

I'm in the process of developing a State Management Library for ReactJs. However, when I integrate it into my React project (built with create-react-app), an error is thrown: Failed to compile. path/to/agile/dist/runtime.js 116:104 Module parse faile ...

A handy application that notifies me of new listings on Craigslist through email, SMS, or RSS feeds

How can I create a software for receiving notifications from Craigslist that sends new postings to my email, SMS, or RSS feed? One scenario is continuously checking the "Free" category for any updates. ...

Creating a Powerful Application with Typescript and NodeJS

Currently, I am attempting to utilize Got with Typescript and ESM. With Got being written in Typescript itself, I anticipated a seamless integration. Alas, even after diligently following this comprehensive guide authored by the creator of Got, I am unable ...

Experiencing difficulties with $watch in my Angular controller

Having trouble getting a $watch function to work properly while testing a controller. In this scenario, the goal is to display ctrl.value in either ARI format or AEP format, but the underlying $scope.model is always kept in the ARI format. When ctrl.value ...

sending a collection of image data arrays wrapped in FormField objects from Angular to Express

I am facing a challenge while trying to upload two FormField objects along with form data to express. I am having trouble using the multer library in express to extract this data from the request. While I can access the form data, the FormField objects re ...

Issue with Ajax submit button failing to pass ID

I am encountering an issue while trying to update data using bootstrap modal. When the CGridView selectionChanged event is triggered, it should call a function to display a modal dialog form and populate the form with the selected data. Below is my CGrid ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...

What sets the target property of the mousewheel event apart from other events like click, mousedown, and touchstart?

The mousewheel event's target property reveals the DOM element currently being hovered over when using the mousewheel or gesture-capable touchpad. In my experience (specifically in Safari 6, I will verify this in other browsers later), the target ret ...

Example of Utilizing Google Places API

The Issue I've been struggling to make this google maps API example function correctly. Even after directly copying the code from Google's website, the example fails to display properly. For instance, the map doesn't show up, the search bar ...

Identifying a web application functioning as a homescreen app within the Android Stock Browser

We are in the process of developing a web application that needs to function as a standalone or homescreen app. While we can identify if it is being accessed from Chrome or Safari using window.navigator.standalone or window.matchMedia('(display-mode: ...

One the year is chosen, it will be automatically hidden and no longer available for selection

<div ng-repeat="localcost in vm.project.localCosts" layout="column"> <md-select name="localcost_{{$index}}"ng-model="localcost.year" flex> <md-option ng-repeat="years in vm.getYears()" ng-value="years">{{years}}< ...

Using html data attributes to encode JSON data with strings

Looking for a way to pass data to JavaScript, I decided to create a template tag as shown below: from django.utils.safestring import mark_safe from django import template import json register = template.Library() @register.simple_tag def mydata(): r ...

Combining Multiple Arrays into a Single Array

Is there a way to combine this merge operation that creates one array using forEach into a single array at the end? affProd.pipe(mergeMap( event1 => { return fireProd.pipe( map(event2 => { const fi ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...