Why isn't this code performing well when trying to alter the styling of DOM elements?

JavaScript is causing major issues and is performing poorly.

Why is this code not working properly??

(this is a back to top button)

function checkScrollTop(){
  if (document.body.scrollTop > 300) {
    document.getElementById("backToTop").style.display = "block";
    setTimeout(function () {
      document.getElementById("backToTop").style.opacity = 1;
    }, 1);
  }else {
    document.getElementById("backToTop").style.opacity = "";
    setTimeout(function () {
      document.getElementById("backToTop").style.display = "";
    }, 300);
  }
}
function backToTop(){
  var x = setInterval(function () {
    if (document.body.scrollTop != 0) {
      document.body.scrollTop -=20;
    }else {
      clearInterval(x);
    }
  }, 1);
}
#backToTop{
  display: none;
  opacity: 0;
  position: fixed;
  bottom: 20px;
  right: 20px;
  transition: 0.3s;
  cursor: pointer;
  background-color: #098774;
  color: white;
  text-align: center;
  font-size: 50px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
  <html>

<body onscroll="checkScrollTop();">
    <div id="backToTop" onclick="backToTop();">^</div>
  <div style="width: 300px;">
http://stackoverflow.com/ads/community?id=so_community_div Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://clc.stackoverflow.com/markup.js?omni=Au0GHyu2P9QIOw2VALkFPwACAAAAAgA…XJlZ2lzdGVyZWR8eC1wZXJzb25hLWZyb250ZW5kfAB8cwIR0hDY2RqW&lw=1959&zc=25&pf=9 Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://stackoverflow.com/ads/community?id=so_community_div Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://clc.stackoverflow.com/markup.js?omni=Au0GHyu2P9QIOw2VALkFPwACAAAAAgA…XJlZ2lzdGVyZWR8eC1wZXJzb25hLWZyb250ZW5kfAB8cwIR0hDY2RqW&lw=1959&zc=25&pf=9 Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://stackoverflow.com/ads/community?id=so_community_div Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://clc.stackoverflow.com/markup.js?omni=Au0GHyu2P9QIOw2VALkFPwACAAAAAgA…XJlZ2lzdGVyZWR8eC1wZXJzb25hLWZyb250ZW5kfAB8cwIR0hDY2RqW&lw=1959&zc=25&pf=9 Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://stackoverflow.com/ads/community?id=so_community_div Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://clc.stackoverflow.com/markup.js?omni=Au0GHyu2P9QIOw2VALkFPwACAAAAAgA…XJlZ2lzdGVyZWR8eC1wZXJzb25hLWZyb250ZW5kfAB8cwIR0hDY2RqW&lw=1959&zc=25&pf=9 Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://stackoverflow.com/ads/community?id=so_community_div Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://clc.stackoverflow.com/markup.js?omni=Au0GHyu2P9QIOw2VALkFPwACAAAAAgA…XJlZ2lzdGVyZWR8eC1wZXJzb25hLWZyb250ZW5kfAB8cwIR0hDY2RqW&lw=1959&zc=25&pf=9 Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://stackoverflow.com/ads/community?id=so_community_div Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER
http://clc.stackoverflow.com/markup.js?omni=Au0GHyu2P9QIOw2VALkFPwACAAAAAgA…XJlZ2lzdGVyZWR8eC1wZXJzb25hLWZyb250ZW5kfAB8cwIR0hDY2RqW&lw=1959&zc=25&pf=9 Failed to load resource: net::ERR_BLOCKED_BY_ADBLOCKER</div>
</body>
  <html>

Watch the video linked below

[url= ] [/url]

Answer №1

Let's give this a fresh rewrite:

opacityLevel=0;
window.onload=function(){
setInterval(function(){
   var element=document.getElementById("backToTop");
  if(element.style.opacity>opacityLevel){
    element.style.opacity-=0.1;
  }else if(element.style.opacity<opacityLevel){
    element.style.opacity+=0.1;
  }
  if(element.style.opacity>0){
    element.style.display="block";
  }else{
    element.style.display="none";
  }
  },100);
  };

Simply set opacityLevel=1; in your code now for a smooth and flicker-free transition.

Answer №2

display should be replaced with visibility!

code update:

function checkScrollTop(){
  if (document.body.scrollTop > 500) {
    document.getElementById("backToTop").style.cursor = "";
    sdocument.getElementById("backToTop").style.visibility = "visible";
    setTimeout(function () {
      document.getElementById("backToTop").style.opacity = 1;
    }, 1);
  }else if (selector("#backToTop").style.visibility == "visible") {
    document.getElementById("backToTop").style.opacity = "";
    document.getElementById("backToTop").style.cursor = "default";
    setTimeout(function () {
      document.getElementById("backToTop").style.visibility = "";
    }, 300);
  }
}
#backToTop{
  visibility: hidden;
}

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 to obtain the following id for an image?

Whenever I hover over the li with the number 3, I am getting the wrong number for the next id in the img tag. The first time, I get next id = 4 which is incorrect. But on the second hover, I get next id = 0 which is what I actually need. How can I correctl ...

Timing of Vue mounting and initialization phases

I am currently working on a component where I pass the reference to an internal element to the parent using defineExpose. In this example, I simply log the element, but in my actual project, I intend to manipulate it. SFC Playground // Comp.vue <scrip ...

The database is failing to reflect any changes even after using the db.insert function

I am currently working on implementing a forgot password feature in my express app using the node mailer package. This functionality involves sending a new password to the user's email and then updating the database with the new password. However, I h ...

What steps are necessary to activate javascript in HTML for WebView?

I recently discovered that when my HTML/JavaScript site is visited via an Android webview, JavaScript is disabled by default. This causes a pricing list on my page to not display properly because it requires a JavaScript class to be added for it to open. I ...

Updating array properties in a JSON object using a foreach loop will automatically update all corresponding keys

Having a slight headache working on this particular issue. My aim is to construct an array of JSON objects using a foreach loop, and everything is functioning perfectly except for one property. The problematic property is actually an array that gets update ...

Encountering a series of frustrating 404 errors when attempting to submit a React form multiple times

I've been working on developing a new forum using Express and React, but I'm facing challenges with saving form data to the database. Currently, my goal is to store topic titles in a MongoDB collection, with plans to expand to include message con ...

Using Vue Js to bind two values to an href attribute in a tag

As a Vue.js beginner, I am encountering an issue where I need to update two values simultaneously during rendering. <ul class="category-list"> <li v-for="category in categories"> <a v-bind:href="location/category.slug/all" v-tex ...

The task "default" is not found within your current gulpfile configuration

After running gulp in my console, I encountered the following error: Task 'default' is not in your gulpfile I double-checked my gulpfile and it appears to be correct: var gulp = require('gulp'), LiveServer = require('gulp- ...

Issues with javascript and php carousel functionality not performing correctly

I am currently in the process of creating a slideshow/carousel for a website. Recently, I implemented a PHP for-loop to iterate through a folder of images, allowing me to use the slideshow with an unspecified number of images. However, after making this ch ...

Is there a way to simulate a minified module for testing purposes?

For my project, I developed a component intended to function as a module. The implementation involves the utilization of third-party code provided in the form of a config file (initOpinionLab.js) and a .min.js file (opinionlab.min.js). As part of the devel ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

Leveraging Ajax for establishing session and displaying outputs

Trying my best to make this work with AJAX, but it's a new concept for me. So bear with me as I figure this out... I've posted a couple of questions about resolving the issue at hand and we've made progress. However, a new challenge has pre ...

Vue.js Components Facing Build Issues

I am currently experiencing a puzzling phenomenon. While working on my application components using Laravel Jetstream and Inertia Stack with VueJS, I encountered an issue where a newly created component in the same folder as others was not building. Neithe ...

Can a JavaScript object be created in TypeScript?

Looking for a way to utilize an existing JavaScript "class" within an Angular2 component written in TypeScript? The class is currently defined as follows: function Person(name, age) { this.name = name; this.age = age; } Despite the fact that Java ...

Is It Possible to Extract a Hidden Document Value from a Web Browser Using IWebBrowser2 in LabVIEW?

After hours of combing through the internet, I've come up empty-handed in my quest to find information related to my current project. I've created an HTML document that gathers user data and stores it in a JavaScript array. This array is then com ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

Issues arise with AngularJS showing images fetched from an API

Currently, I am facing an issue where I am trying to display images from a REST API but keep receiving a "error 403" message. Here is the link to my JSFiddle. Please take a look, as I have attempted using both <img src=""> and ng-src='', bu ...

modify the tr element within a jQuery context

I am attempting to convert a "yes" to a select dropdown that allows users to choose between yes and no. The HTML structure is as follows: <tr> <td>text</td> <td>no (needs to be changed via JS)</td> <td><a href="#"&g ...

Is it possible to retract a message on Discord after it has been sent?

I have a code that automatically sends a welcome message when a new member joins the guild, and I want it to be deleted shortly afterwards. Here is my current code: client.on('guildMemberAdd', (member) => { var server = member.guild.id; i ...

Best Practices for Variable Initialization in Stencil.js

Having just started working with Stencil, I find myself curious about the best practice for initializing variables. In my assessment, there seem to be three potential approaches: 1) @State() private page: Boolean = true; 2) constructor() { this.p ...