AngularJS + Material's smooth scroll feature allows you to effortlessly navigate back to

Have you seen the button on the AngularJS Material website? It's a round red button labeled as md-fab-button, located at the bottom right corner. I wonder where I can find the code for this button since there is no clear description provided.

Below is an example code snippet using AngularJS and Material, without the scroll-up button, similar to what I am currently using:

'use strict';
const application = angular.module("application", ['ngMaterial']);
application.controller('applicationCtrl', ['$scope', function(scope) { }]);
<head>
  <link rel="stylesheet" href="https://material.angularjs.org/1.1.20/angular-material.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
  <script src="https://code.angularjs.org/1.7.8/angular-animate.min.js"></script>
  <script src="https://code.angularjs.org/1.7.8/angular-aria.min.js"></script>
  <script src="https://material.angularjs.org/1.1.20/angular-material.min.js"></script>
</head>

<body ng-app="application" ng-controller="applicationCtrl" ng-init="onInit();" layout="column" class="ng-cloak" style="overflow: hidden;">
  <!-- Top menu -->
  <md-toolbar class="md-toolbar-tools md-hue-2" md-scroll-shrink>
    <!-- Main -->
    <a href="https://example.com/">
      <md-button>
        <b class="md-title">Main page</b>
      </md-button>
    </a>
  </md-toolbar>
  <md-content flex layout="column">
    <!-- Page header -->
    <div>
      <div layout="row" flex="100" md-whiteframe="1">
        <div flex layout="row" layout-margin layout-align="center center">
          <span class="md-display-1">Learning to write programs</span>
        </div>
      </div>
    </div>
    <!-- Page content -->
    <div layout="column" layout-padding layout-wrap style="flex-grow: inherit;">
      <div layout="row" layout-align="center center" md-whiteframe="1">
        <span class="md-display-1">Hello world</span>
      </div>
      <div layout="row" layout-align="center center" md-whiteframe="1">
        <span class="md-display-1">Hello space</span>
      </div>
      <div layout="row" layout-align="center center" md-whiteframe="1">
        <span class="md-display-1">Hello universe</span>
      </div>
      <div layout="row" layout-align="center center" md-whiteframe="1">
        <span class="md-display-1">Hello Santa Claus</span>
      </div>
      <div layout="row" layout-align="center center" md-whiteframe="1">
        <span class="md-display-1">Hello stars</span>
      </div>
      <div layout="row" layout-align="center center" md-whiteframe="1">
        <span class="md-display-1">Hello everyone</span>
      </div>
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
      <span>Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi...

Answer №1

If you're looking for the code behind the original button, you can find it here. It uses an undocumented factory called $mdUtil for scrolling, includes a custom directive named docsScrollClass for visual effects, and has some custom CSS styling.

However! In my scenario, this code doesn't function properly because it utilizes the md-scroll-shrink attribute which causes the header to shrink away while scrolling down.


The standard code snippet looks like this:

'use strict';
const app = angular.module("app", ['ngMaterial']);
app
  .controller('appController', ['$scope', '$mdUtil',
    function($scope, $mdUtil) {
      let mainContent = document.querySelector("main");
      let scrollEl =
        mainContent.querySelector('md-content[md-scroll-y]');
      $scope.scrollTop = function() {
        $mdUtil.animateScrollTo(scrollEl, 0, 200);
      }
    }
  ])
  .directive('docsScrollClass', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attr) {

        let scrollParent = element.parent();
        let isScrolling = false;

        // Initial update of the state.
        updateState();

        // Register a scroll listener, which updates the state.
        scrollParent.on('scroll', updateState);

        function updateState() {
          let newState = scrollParent[0].scrollTop !== 0;

          if (newState !== isScrolling) {
            element.toggleClass(attr.docsScrollClass, newState);
          }

          isScrolling = newState;
        }
      }
    };
  });
// The rest of the code remains unchanged
// Include all other snippets as well


In my case:

// Update your solution here by pulling out the button outside from md-content into main. Don't modify $mdUtil or the CSS styles, only tweak the docsScrollClass directive for better display results.


Resolution:

To enhance functionality with both md-scroll-shrink on and off, adjust the structure based on the given template.

Here's the updated script that caters to both scenarios:

// Updated application code with new scroll functionalities
// Add updated directive for smoother scrolling effect
// Updated CSS classes for proper animation control
<!-- Your HTML/Body content goes here -->
// Insert final updated markup structure here


For more details, refer to this article on "Scroll-up fab-button".

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

The default styling of Next.js react-chatbot-kit is not functioning properly

import Chatbot from 'react-chatbot-kit' import config from './config' import ActionProvider from './actionProvider' import MessageParser from './messageParser' const ChatBotFlight = () => { return ( <div> ...

What steps are needed to enable Azure AD authentication using msal-browser for a Next.js application in a production environment?

While testing my implementation of msal on localhost, everything runs smoothly. However, once deployed to an Azure App Service, the clientId or tenantID values appear to become undefined. I even attempted hardcoding the id strings into the file but still e ...

Extracting JSON Data into Text Boxes within jQuery UI Dialogs

Let me provide some context to my current issue. Due to the nature of the problem being work-related, I am unable to share much of the code. The task at hand involves working with a jQuery dialog. Essentially, I have a list of names displayed with a boots ...

How do I send a 404 error in Node JS Express when a third party API receives a bad request?

I've set up a Node JS server with a route handler that sends a request to a third-party API to retrieve a username: app.get('/players/:player', apiLimiter, function(request, response) { const player = request.params.player; const api_url = ...

muiSlider limited to specific range

I am currently using the Mui Slider component for a user interface where I need to restrict its value within a certain range. For example, I want the slider's handle to become unmovable after reaching 50. Users can still select values up to 50, but th ...

The HTML required attribute seems to be ineffective when using AJAX for form submission

Having trouble with HTML required attribute when using AJAX submission I have set the input field in a model Form to require attribute, but it doesn't seem to work with ajax. <div class="modal fade hide" id="ajax-book-model" a ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

Using Redux with Next.js to implement getStaticPaths

Can someone help me understand how to implement getStaticPaths in conjunction with Redux in Next.js? I'm currently using next-redux-wrapper to manage my content, but I am encountering issues when trying to display the data. Below is a snippet of my ...

What is the best way to sum the numbers in this code snippet?

I'm trying to iterate through an array called arr = [[1,2],4] using for loops to access the numbers. However, I've noticed that I can't seem to add the last number for some reason. Can anyone explain why this is happening? let arr = [[1, ...

Access my account on the one.com control panel using the identical login credentials

I am curious if it's possible to implement a login page on my website for customers and then seamlessly redirect them to the control panel on one.com without requiring them to re-enter their username and password? Visit the action page on one.com her ...

Transferring information from a $scope to a separate function within AngularJS

Currently, I am struggling with passing data from the $scope.abc() function to another actual function. [Function] function sweetAlertCtrl($scope, SweetAlert, $state) { $scope.demo1 = function () { SweetAlert.swal({ title: "Good j ...

accessing deeply nested JSON objects during the process of mapping data from an API request

Currently, I am in the process of integrating JSON into Data-driven rendering using React. To achieve some of my objectives, I will need to work with Nested JSON structures. However, during the mapping of this data, I have encountered some difficulties in ...

Swap out the variables in your function with the values selected from the dropdown menu

I've recently started delving into writing JS functions and I'm facing a challenge with the following scenario: On an HTML page, I want to change a variable within a lodash function based on the value of a dropdown and display the result in a HT ...

Is there a way to execute all functions with their respective arguments simultaneously using just one `run()` command?

Imagine having two separate files to work with: File 1 exports.run = () => { console.log(test.property, test2.property, etc.property) }; exports.info = { name : "test" } File 2 const fs = require('fs'); let test; let test2; ...

When attempting to utilize VueJs v-bind:type on an input element, it appears to be ineffective when the type property name is

Code: <!DOCTYPE html> <html> <head> <title>Creating a Vue app</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3046455570021e061e0100">[ ...

Problem encountered with a selection menu

I'm experiencing some trouble with the dropdown menu. Whenever I try to move the mouse to access the dropdown menu, it seems unresponsive. I attempted adjusting the padding on a line of code but ended up moving the entire line instead. Here is the cod ...

Creating a new application to manage and oversee my mathematics classes

As a mathematician with experience in programming, I run a successful (Math) YouTube channel and offer paid math courses. I am looking to create a web application or customize an existing template that will enable me to manage access to my classes (priva ...

The functionality of Protovis JavaScript is not supported within a dropdownlist's onchange event

I encountered an issue where one block of code works fine on its own, but when combined with another block, only one of them functions properly. The problem arises when I try to invoke a method from a dropdownlist using the onchange event, especially afte ...

Utilized OBJLoader to load an item successfully; now seeking guidance on calculating the coordinates of an element within (three.js)

I am utilizing three.js and OBJLoader to create a 3D human head representation: let renderer, camera, scene, head, light, projectiles; new THREE.OBJLoader().load(objUrl, initialize); function initialize(obj) { renderer = new THREE.WebGLRenderer({ al ...

Utilize array.prototype.reduce() with strings

I'm puzzled about how the reduce operation is carried out on a string. Initially, a new Str instance is created with the desired string as a parameter. Following that, the split method is used to divide the string into an array of strings. A method c ...