Javascript window.scroll function malfunctioning in some browsers while running in localhost

Check out this codepen link where everything is working, but unfortunately not locally:

https://codepen.io/LoudDesignStudios/pen/RwxPJKY

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="assets/css/css1.css">
</head>
<body>
<section id="about-us" class="">
s1
</section>
<section id="why-choose-us" class="">
s2
</section>
<section id="funfacts" class="">
s3
</section>
<section id="services" class="">
s4
</section>
<section id="studio" class="">
s5    
</section>
<section id="contactus" class="">
  s6    
</section>
<section id="footer-widgets" class="">
 s7       
</section>
<footer id="footer" class="footer">
  footer      
</footer>
<button onclick="topFunction()" id="scrollUp"><i class="las la-chevron-up" aria-hidden="true"></i></button>
<script>
var mybutton = document.getElementById("scrollUp");
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 60 || document.documentElement.scrollTop > 60) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}

function topFunction() {
  document.body.scrollTop = 0;
  document.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
</script>   
</body>
</html>

The same codes are functioning perfectly on other websites that were created a while ago. However, when starting from scratch now, the window.scroll function is not triggering.

Thank you for your help.

Answer №1

The reason for the issue you're facing is that you are attempting to select an element (mybutton) by its ID before the entire document has finished loading.

To resolve this, you will need to enclose your code within a DOMContentLoaded event handler. Here is a slightly altered version of your JavaScript code:

    document.addEventListener("DOMContentLoaded", function () {
      var mybutton = document.getElementById("scrollUp");
      window.onscroll = function () { scrollFunction() };

      function scrollFunction() {
        if (document.body.scrollTop > 60 || document.documentElement.scrollTop > 60) {
          mybutton.style.display = "block";
        } else {
          mybutton.style.display = "none";
        }
      }
    });

    function topFunction() {
      document.body.scrollTop = 0;
      document.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    }

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

What is the best method for displaying plain text using the br tag?

My component looks like this: class News extends Component { state = { isSimple: this.props.isSimple } render() { return ( <div> <div className="extended">extended</div> simple text </div&g ...

Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below: function animate() { requestAnimationFrame(animate) spher ...

Issues arise with AJAX authentication request

Currently, I'm working on incorporating a basic login form with an AJAX request that forwards the user to a page for querying my database. Depending on the results, the user is then redirected to the main index page or prompted back to the login form. ...

What is the best way to ensure the proper formatting of my initial form?

Hello, I am encountering some challenges with formatting my form. As a beginner in web coding, I apologize for what may seem like a simple issue - this is the first form I am attempting to code. My objective is as follows: On screens and tablets: have fo ...

Creating visual content on a website

I'm currently working on a project where I need to showcase the results of a numerical model I am operating. My goal is to gather user input in the form of latitude/longitude coordinates, utilize php (or a similar tool) to trigger a python script that ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

What is the best way to show personalized messages to users using modal windows?

Encountering bugs while trying to implement user messages in modals. function displayMessage(title, description) { var myModalErrorMessage; $("#customErrorMessageTitle").text(title) $("#customErrorMessageDescription").html(description) myModalEr ...

Push Button Unleashes a Cascade of Buttons

After creating a dropdown button, I encountered an issue where replicating it multiple times resulted in all the buttons on the page opening simultaneously. I initially thought that wrapping the button in a class called "dropdown" would prevent this from h ...

Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error: jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error) This is my controller ...

What is the best way to notify the user about the input in the textbox?

Imagine you have a button and an input field. How could you notify the user of what is in the input field when the button is pressed? Please provide a simple explanation of your code. ...

Strategies for determining the direction of a slide event within a Bootstrap carousel

I am attempting to identify the direction of the slide in a Bootstrap 4 carousel when the user initiates the slide event. Is there a method to achieve this? $('#myCarousel').on('slide.bs.carousel', function () { //Determine wheth ...

Dynamic parallax or stacked vertical text animation

I am attempting to replicate the text effect found on . The text is centered both vertically and horizontally within each div, but as you scroll down, the top position shifts creating a parallax effect. As you continue scrolling, the text transitions to th ...

Error in AngularJS and TypeScript: Property 'module' is undefined and cannot be read

I'm attempting to incorporate TypeScript into my AngularJS 1.x application. Currently, my application utilizes Webpack as a module loader. I configured it to handle the TypeScript compilation by renaming all *.js source files to *.ts, and managed to ...

Leveraging mongo aggregate functionality within the meteor framework to calculate the total number of unlocked and locked

So, I have a collection where I store documents related to users with a structure like: {_id: "hofjew233332j4", userId: "fhewojfw34324", achievementUnlocked: true }; My goal is to use the aggregate and underscore functions to group the documents by user ...

Resolve the issue of Dojo images not appearing on a div in Internet Explorer

I am trying to incorporate images into a dojo chart using the given code: var l_images = ["images/clearnight.png","images/clear.png","images/partlyCloudy.png","images/cloudy.png","images/showers.png","images/rain.png","images/thunderstorms.png","images/ic ...

Store the current user's authentication information from Firebase in the Redux state using React-Redux

I am facing an issue with persisting the state of my redux store using the currentUser information from Firebase Auth. The problem arises when I try to access auth.currentUser and receive null, which I suspect is due to the asynchronous loading of the curr ...

Tips for making Ajax crawlable with jQuery

I want to create a crawlable AJAX feature using jQuery. I previously used jQuery Ajax on my website for searching, but nothing was indexed. Here is my new approach: <a href="www.example.com/page1" id="linkA">page 1</a> I display the results ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

Error: req.next is not a recognized function in node.js

I am completely stumped by this sudden issue that just appeared out of nowhere, with no changes in the code! TypeError: req.next is not a function The error is occurring at line 120. Here is the corresponding SQL query and the problematic line 120: // Set ...