Mobile website scroll assistant

Seeking a solution to aid mobile users in scrolling through a lengthy article page. Typically in mobile apps, an alphabetical index assists users in navigating long lists. How can I incorporate a similar feature into a webapp?

For context, my tech stack includes angularjs, jquery, and phonegap.

Answer №1

To easily scroll to a specific section in your Angular application, utilize the built-in $anchorScroll service provided by Angular.

For a detailed demonstration, refer to the live example available on Angular's official documentation. Below are the essential code snippets:

Include the following in your view template:

<div id="scrollArea" ng-controller="ScrollCtrl">
  <a ng-click="gotoBottom()">Go to bottom</a>
  <a id="bottom"></a> You're now at the bottom!
</div>

Add this code snippet to your controller:

function ScrollCtrl($scope, $location, $anchorScroll) {
  $scope.gotoBottom = function (){
    // Set the location.hash to the ID of
    // the element you want to scroll to.
    $location.hash('bottom');

    // Invoke $anchorScroll()
    $anchorScroll();
  };
}

Answer №2

iOS7 Style List Navigator

If you're looking for a sleek mobile interface, check out my iOS7 style list navigator. I found Apple's solution to be very intuitive, so we borrowed it.

This code assumes that you won't need to scroll the body, as many smartphone designs allow fixed headers and footers for Android versions less than 4 without any issues.

A quick note: this code is fresh and hasn't been thoroughly tested yet.

CHECK OUT DEMO AND CODE

CSS (excerpt)

#scrolling {
    padding-top: 44px;
    overflow: scroll;
    -webkit-overflow-scroll: touch;
    height: 100%;
}
.menu {
    position: fixed;
    right: 0;
    font-size: 12px;
    text-align: center;
    display: inline-block;
    z-index: 2;
    top: 58px;
}

.list .divider {
    position: -webkit-sticky; /* stops label when reaching header */
    top: 44px;
}

HTML (excerpt)

<div id="scrolling">
<ul class="menu">
    <li><a href="#a">A</a></li>
    <li><a href="#b">B</a></li>
    <li><a href="#c">C</a></li>
    <!-- more list items -->
</ul>
<ul class="list">
   <li class="divider" id="a">A</li>
   <li><a href="#">Amelia Webster</a></li>
   <li><a href="#">Andrew Wilkinson</a></li>
   <!-- more list items -->

Javascript (zepto/jquery)

$(function() { 
  $(window).on("touchstart touchmove mouseover click", ".menu a", function(e) {
    e.preventDefault();
    clearInterval(t);
    var steps = 25;
    var padding =  68;
    var target = $( $(this).attr("href") ).next("li");
    if ( target.length > 0 ) {
        var scroller = $("#scrolling")[0];
        var step = parseInt((target[0].offsetTop - padding - scroller.scrollTop)/steps);
        var stepno = 0;
            setInterval( function() {
                if ( stepno++ <= steps  ) {
                    scroller.scrollTop += step;
                } else {
                    clearInterval(t)
                }
            }, 20);
    };
  });
});

The code checks link validity before attempting to scroll. Feel free to adjust the padding value to suit your needs.

Keep in mind that we are targeting the first element after the specified target due to Safari's behavior with sticky positioning.

This code utilizes jQuery/Zepto selectors for simplicity and readability, but these libraries aren't necessary. With a bit more effort, you can achieve the same result without dependencies.

http://codepen.io/frapporti/pen/GtaLD

Answer №3

If you're looking for a way to implement a toggleable sidebar, check out this example. To get a better idea, try resizing your browser to mimic a mobile phone screen.

To achieve smooth scrolling to specific parts of an article in AngularJS, you can create a directive that wraps jQuery's animate function. Here's an example:

angular.module('yourModule', [])
       .directive('scrollTo', function() {
          return {
           restrict : 'EA',
           link: function(scope , element, attr){
                   $('html, body').animate({
                      scrollTop: $( attr['href'] ).offset().top
                    }, 300);
                 }
          };
       });

Simply use the id of the section as the value of the href attribute. Then apply the directive to the links in your sidebar like so:

... 
<li><a href="#section-1" scroll-to>Jump to section 1</a></li>
...

I hope this information proves useful!

Answer №4

If you're searching for a solution, check out this link:

I haven't personally tested it, but it appears to be straightforward to start using.

Answer №5

If you're looking for a solution, I have something in mind that might be suitable for your needs. Take a look at this example: http://codepen.io/aecend/pen/AsnIE. It's a simple prototype I quickly put together to demonstrate the concept. I can definitely elaborate on it further if necessary. Essentially, it features a translucent bar on the right side of the screen that identifies article headings (which can be customized) and adds clickable/tappable links to navigate to each article. Upon clicking one, the page smoothly scrolls to the selected article. There are more enhancements that could be implemented to enhance usability, but this serves as a proof of concept.

CSS

#scrollhelper {
  position: fixed;
  top: 0;
  right: 0;
  height: 100%;
  width: 5%;
  background-color: rgba(0,0,0,0.2);
  overflow: hidden;
}

#scrollhelper .point {
  position: absolute;
  display: block;
  width: 100%;
  height: 10px;
  margin: 0 auto;
  background-color: rgba(0,0,255,0.5);
}

JavaScript

var articles;

function buildScrollHelp() {
    var bodyHeight = $("body").height();
    var viewHeight = window.innerHeight;

    $("#scrollhelper").html("");

    articles.each(function() {
        var top = $(this).offset().top;
        var element = document.createElement("a");
        element.className = "point";
        element.href = "#" + $(this).attr("id");
        element.style.top = ((top / bodyHeight) * viewHeight) + "px";
        $(element).on("click", function(e){
            e.preventDefault();
            $('html, body').animate({
                scrollTop: $($(this).attr("href")).offset().top
             }, 500);
        });

        $("#scrollhelper")[0].appendChild(element);
    });
}

$(document).ready(function() {

    articles = $("body").children("[id]");
    $("body").append("<div id=\"scrollhelper\"></div>");

    $(window).resize(function(){
        buildScrollHelp();
    });

    buildScrollHelp();

});

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

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

Issue with Protractor locating element even though everything appears to be in order

I'm having trouble locating this element with Protractor. It's really frustrating me. I double-checked in the dev console and the element definitely exists. Any suggestions on why it's not being found? <download path="api/backup_jobs/e ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

Discover the exclusive Error 404 dynamic routes available only in the production version of NEXT13! Don

Hey everyone, I'm encountering an issue with NEXT's dynamic routing (Next 13). My folder structure looks like this: - user/ -- [id]/ --- page.js It works fine in dev mode but not in production. What am I trying to do? I've created a "page ...

Organize results from MySql using php

Trying to retrieve table values from a MySQL database sorted has proven to be a challenge for me. While I am able to connect and update the table successfully, I struggle with displaying the messages in the HTML chat history sorted by time. Is there a mo ...

Is there a way to imitate a method that initiates an AJAX request?

I am currently working on writing tests for my Angular application and I need to mock a method in order to avoid making actual requests to the server. Within my grid.service.ts file, here is the method I am trying to mock: loadAccountListPromise(id: str ...

Solving an object in ui-router state using ui-sref

Dealing with a large JSON object in an Angular controller and wanting to pass it to the controller of a template that will be displayed in a ui-view. I am aware that parameters can be passed to states using ui-sref, but I do not want this object to be visi ...

Transmitting a vast amount of data through a single stream using NodeJS and ExpressJS

I am currently in the process of creating a prototype for an application using the native mongo rest api. In this scenario, Node returns approximately 400K of JSON data. To make the request to mongo's native API and retrieve the result, I am using the ...

Issue encountered when attempting to serve JSON response using Node.js, express, and MongoDB after the initial response

I have been experimenting with creating simple RESTful APIs using Node.js, Express, and MongoDB. For this purpose, I am utilizing the Node.js-MongoDB driver in conjunction with the Express framework. const MongoClient = require("mongodb").MongoClient cons ...

Confirmation message is displayed upon clicking to delete a row in the editable Gridview, prompting the user to

One issue I am facing is with a Delete button in an editable Gridview on my ASP.NET application. When the delete button is clicked, it triggers a function that displays a confirmation popup asking the user for feedback on whether they want to proceed with ...

transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated. var array = []; var maxLength = 3; var delay = 250; //Shortened the delay var ticker = {}; ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this: var myArray = ("0% { left:74px; top:202px; }" , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" ); Within the array, there are 2 entries that ha ...

Troubleshooting 404 Error When Using Axios Put Request in Vue.js

I'm trying to update the status of an order using Axios and the Woocommerce REST API, but I keep getting a 404 error. Here's my first attempt: axios.put('https://staging/wp-json/wc/v3/orders/1977?consumer_key=123&consumer_secret=456&apos ...

An excellent server-side resolution for the Angular.js

Currently, I am utilizing Angular.js for my project. The core logic of the business is developed within Angular and there are two specific areas I really need assistance with: I am in search of a seamless method to authenticate users, but I'm unce ...

Is there a way to check if a file name input is valid using regular expressions?

I'm having trouble getting my code below to work properly. I'm not sure if the problem lies in the match function syntax or the regex itself. Any assistance would be greatly appreciated. $scope.fileSelected = function (file) { var valid = "/ ...

Angular dropdown menu with 2 options

Looking to implement a select box with various price ranges to choose from. For example: - 0 to $2,000 - $2,000 to $3,500 - $3,500 to $5,000 - $5,000 to $7,500 - $7,500 to $10,000 - $10,000 Once a user selects an option, I want to automatically set the ...

Integrating an external JavaScript library into the codebase

I created a web radio player using Vue Cli and now I need to incorporate a new feature with an external library, specifically designed for handling audio advertisements. The catch is that this library must be loaded from a remote server and cannot be simpl ...

Error message when trying to get tree from Json using jqTree: "Oops! $(...).tree is not a valid function."

Currently, I am utilizing jqTree to display JSON data in a tree format. However, as I was implementing the demo of jqTree, an error occurred: "Uncaught TypeError: $(...).tree is not a function" ...

What is the reason behind the absence of compile time errors when using 'string' functions on an 'any' field type variable in TypeScript?

Looking at the following typescript code snippet: let a; a = "number"; let t = a.endsWith('r'); console.log(t); It is worth noting that since variable 'a' is not declared with a specific type, the compiler infers it as ...