The back-to-top feature is malfunctioning in the new Bootstrap 4 update

I've been working on adding a back-to-top button to my website using JavaScript in Bootstrap 4 with the Font Awesome icon set. It was functioning perfectly until I made some changes to the site, and now it's not working anymore. I'm pretty new to JavaScript and can't figure out what went wrong...

This is the code I have:

$(document).ready(function() {
        $(window).scroll(function() {
          if ($(this).scrollTop() > 50) {
            $('#back-to-top').fadeIn();
          } else {
            $('#back-to-top').fadeOut();
          }
        });
        
        $('#back-to-top').click(function() {
          $('body,html').animate({
            scrollTop: 0
          }, 400);
          return false;
        });
      });
.back-to-top {
    position: fixed;
    bottom: 25px;
    right: 25px;
    display: none;
}
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height:100rem;">test</div>
<a id="back-to-top" href="#" class="mr-m2b btn btn-primary btn-lg back-to-top" role="button">TOP<i class="fas fa-chevron-up"></i></a>

It used to work flawlessly until something caused it to stop working. The JavaScript seems to be the issue as it's not doing much, but I'm unsure why. Why did it work before without any changes to the function?!

Edit: I recently removed a custom scrollbar

body::-webkit-scrollbar {
  width: 1em;
}

body::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

body::-webkit-scrollbar-thumb {
  background-color: #A1394F;
  outline: 1px solid slategrey;
}

Adding the deleted scrollbar back didn't solve the issue either. The same JavaScript code works fine here, but not on my HTML page... What am I overlooking?

Answer №1

If your code isn't functioning as expected in your project, you can try the following solution:

Instead of using "body, html" or creating an id for the body element like <body id="top">, modify your JavaScript to target the newly created id like so:

document.querySelector('#top').scrollIntoView({ behavior: 'smooth' });

For a smoother scrolling experience, you can also explore this resource:

JavaScript

// Scroll to Top
$(document).ready(function(){

    // Check if window is scrolled past a certain point and display button
    $(window).scroll(function(){
        if ($(this).scrollTop() > 800) {
            $('#back-to-top').fadeIn();
        } else {
            $('#back-to-top').fadeOut();
        }
    });

      // Scroll to top functionality
      document.querySelector('.back-to-top').addEventListener('click', function(e) {
        e.preventDefault();
        document.querySelector('body').scrollIntoView({ behavior: 'smooth' });
      });

});

Answer №2

After encountering an issue, I was able to resolve it by simply re-copying the JavaScript script and pasting it at the end of the body section. The root cause of the problem turned out to be related to the incorrect import order rather than any issues with the code or versions being used. Surprisingly enough, ensuring that Jquery 3.3, 3.4, and 3.5 all function properly comes down to having the correct import order in place.

<script src="{% static 'jquery-3.5.1.min.js' %}"></script>
<script src="{% static 'popper1.16.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $(window).scroll(function() {
      if ($(this).scrollTop() > 50) {
        $('#back-to-top').fadeIn();
      } else {
        $('#back-to-top').fadeOut();
      }
    });
    // scroll body to 0px on click
    $('#back-to-top').click(function() {
      $('body,html').animate({
        scrollTop: 0
      }, 400);
      return false;
    });
  });
</script>

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

Transform the elements of a tensor in TensorFlow into a standard JavaScript array

Having utilized the outerProduct feature within the TensorFlow.js framework on two 1D arrays (a,b), I am faced with a challenge in obtaining the values of the produced tensor in regular JavaScript format. Despite attempts using .dataSync and Array.from(), ...

The method for retrieving and entering a user's phone number into a text field upon their visit

Objective: To enhance the user experience by automatically filling in the phone number input field when a mobile user views the page, making it easier to convert them into leads. A privacy policy will, of course, be in place. This page will offer a promo ...

Deselecting checkboxes inside a specific div using jQuery when a separate checkbox is clicked

In this scenario, there are two distinct divs: check_one and check_two. Within check_one, there are 4 checkboxes, while check_two only has 1. The objective is to create functionality where checking the checkbox within check_two will automatically uncheck ...

"Reacting to click events, all buttons have been successfully updated in ReactJS

When a button is clicked, all buttons are updated simultaneously. However, I am looking to only change the state of the specific button that is clicked. Please refer to the image links and code provided below. import React from 'react'; import & ...

Issues with functionality of Bootstrap carousel slider

Currently, I'm attempting to put together a Bootstrap carousel slider with indicators by referencing the Bootstrap code. The caption setup is functioning as expected, but I'm encountering issues with the slider itself. The problems I'm faci ...

Guide on setting up JSME, a chemistry portal integrated with JavaScript, within vuejs

I am looking to integrate the JSME chemistry portal into my Vuejs application. Upon the initial page load, an error is displayed: JSME initialization error: HTML id jsme_container not found. Strangely, upon refreshing the page, the error disappears. How ...

Learn how to divide a container div with multiple sub-divs into two columns using CSS

Are you up for a good challenge? In my MVC project, I have a dynamic list of divs that I want to split into two columns. The number of divs in the list is unknown. How would you go about achieving this task? EDIT: Just to clarify, when I say split, I&a ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

Css animations not functioning properly in Chrome

I've been working on this animation project, here is the link: http://codepen.io/Zeaklous/pen/dIomg It seems to work perfectly fine on Firefox but not on Chrome. Here is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/ ...

Instructions for inserting an anchor tag into the middle of a <p> element utilizing document.createElement("p")

When generating elements dynamically with JavaScript using document.createElement("p"), I am looking to create a paragraph element <p></p> that includes an anchor tag in the middle, creating a clickable link within the text. I aim to use JavaS ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Understanding the performance of video in threejs when using getImageData

Edit; Check out the working codepen (you'll need to provide a video file to avoid cross-origin policy) https://codepen.io/bw1984/pen/pezOXm I'm currently trying to adapt the amazing rutt etra example from to utilize video (using threejs), but ...

Working with an array of object in Vuex for form handling

Looking to make updates to a vuex store that includes an array of objects: Users have a combobox for making selections, which then updates a property of the object in the database. However, every time I choose an item from the autocomplete (combobox) I e ...

What is the best way to extract the name from JSON data?

I have a list of items in my HTML with data attributes. When a user clicks on one of the items, I want to display or append a list of related suburbs for that selected item in another list. This is being achieved using ajax. <ul id="cities"> <l ...

The functionality of multiple UI-Views is not meeting the intended outcomes

I'm facing an issue with integrating multiple UI-views in my AngularJS dashboard app. Despite following the directory structure, I am unable to get it working as expected. This is how my directories are organized: index.html app/ app.js dash ...

Is there a way to modify the automatic zoom feature in Bootstrap 4 Carousel that adjusts the image to fit a certain section?

Is it possible to change the specific area that is zoomed into in the image? While having the correct resolution would be ideal, I am unsure of the optimal resolution for the carousel. To see a demonstration, click on this link: https://jsfiddle.net/rmbe ...

Are there any npm modules available that can efficiently transform unstructured information into a CSV format?

In my Javascript project, I am trying to export data into a CSV file. However, I am facing an issue as the data I have may contain different headers for each row. For example, the data structure could be like this: [ { name: 'John', color: &apo ...

CURL is spitting out garbage data

I've been attempting to scrape data from the 538 baseball odds website. When I paste the URL into Chrome and check the source code, it appears to be standard HTML. However, when I try to extract the data using the following code snippets or file_get ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

Apple's iPhone does not adhere to media query specifications

My responsive website was functioning perfectly on desktop, Android, and Windows Phone devices. However, when I asked my friends to check it on their iPhones running iOS 10, they informed me that the media queries were being ignored on iPhone models 5, 5s, ...