When I use the scrollTop() jQuery method, my browser starts to lag after scrolling

I'm in the process of creating a single page scroll website and everything seems to be working smoothly. However, I've encountered an issue with the scroll to top functionality. When I reach the top of the page and try to scroll down again, the site becomes unresponsive. Can someone help me identify any mistakes in my jQuery code?

The problem seems to be more prominent in Firefox. You can view the issue here: http://jsfiddle.net/swapnesh/jSa3z/

Script:

<script>
jQuery(document).ready(function(){
    $('section[data-type="background"]').each(function(){
        //assigning the object
        var $bgobj = $(this);

        $(window).scroll(function(){
            var yPos = $(window).scrollTop() / $bgobj.data('speed');

            var coords = '50%' + yPos + 'px';

            //Move the background
            $bgobj.css({ backgroundPosition : coords });
        })
    })

    $(window).scroll(function(){
        if( $(this).scrollTop() > 600 ) {
            $('#scrollpage').fadeIn();
            $('#scrollpage').click(function(){
                $("html, body").animate({ scrollTop: 0 }, 600);
                return false;
            })
        }
        else {
            $('#scrollpage').fadeOut();
        }
    })
})
</script>

HTML:

<section id="home" data-type="background" data-speed="10" class="pages">
    <article>Swapnesh Sinha</article>
</section>

<section id="about" data-type="background" data-type="10" class="pages">
    <article>Web Developer - PHP, MYSQL, WORDPRESS</article>
</section>

<div id="scrollpage"></div>

Answer №1

The scrollPage element does not need to be dynamically created, so you only have to attach the clock event handler once (outside of the window scroll event handler)

$('#scrollpage').click(function(ev){
    ev.preventDefault();
    $("html, body").animate({ scrollTop: 0 }, 600);
})

$(window).scroll(function(){
    if( $(this).scrollTop() > 600 ) {
        $('#scrollpage').fadeIn();
    }
    else {
        $('#scrollpage').fadeOut();
    }
})

Check out the updated fiddle here: http://jsfiddle.net/jSa3z/3/

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 way to dynamically update HTML Select elements using Ajax when other Select elements change?

Currently, I have a search page featuring 7 select dropdowns and 2 textfields. The options in the selects are pulled from a MySQL database. I am looking to implement a functionality where when I make a selection in one of the dropdowns, the other selects ...

ExpressJS routes that are custom made by users

Some websites offer users the ability to create custom sessions with a unique link, such as https://website.com/session/UniqueRandomID. I have a basic understanding of custom routes in ExpressJS, but I am unsure how to allow users to create these sessions ...

The $(Document).ready function does not trigger in the code but functions properly when executed in the console

I'm having an issue with a script that works in the console but not on the actual code. I tried using $(windows).ready, but it still doesn't work. Here is the script: <script> console.log('1') $(document).ready(function( ...

Issues with Display on IE 11 and Edge

Currently, I am in the process of working on a website that was initially created from a template by someone else. Since I am not a professional web designer, some elements on the site are not my own creation. Everything seems to be running smoothly on Fir ...

Form tag definitions are missing on the login page

Here is a snippet of code I am using: <%= form_tag :action => 'process_login'%> Username: <%= text_field "user", "fullname" %>&#x00A; Password: <%= password_field "user", "password" %>&#x00A; <%= submit_t ...

Creating gaps between flexbox divs for a more visually appealing layout

I am curious about the best practices for creating spacing between two divs that use flexbox. For example: https://i.sstatic.net/OZ8cp.png header { background-image: radial-gradient(circle, #72d6c9, #54d1ed, #7ac5ff, #bcb2fe, #f29cd9); height: 80px ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Div over which scroll editing is performed

I want to develop a website where my title div remains fixed in one position as I scroll down. However, the issue arises when I set it to be fixed because my navigation button on the left disappears and I'm unsure how to keep it in place. // JavaSc ...

Is the JSON returned by the API server not being properly processed by the RequireJS module, resulting

After extensive research on promises and module creation, I am still unable to understand why my current setup is not functioning properly. My goal is to write a script that takes a username and then fetches user data from a 3rd party API using a separate ...

Ajax is working effectively as the first post is successful and the second post is able to retrieve data

UPDATE: I resolved the issue by relocating my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). By doing this, the functions are always re-loaded and attached to the "new" form each time the div is refreshed. ...

Exploring an array of JSON data with HandlebarsJS and BackboneJS

My goal is to showcase a collection of music artists organized by the first letter of their name. This is how I have set up my Backbone View: function (App, Backbone, utils) { // Define a new module. var AllArtists = App.module(); // Create ...

Issue: Undefined onClick function for HTML when using Node.js, NPM, and Parcel

I am currently working on a weather application using Node.js, NPM, and Parcel for development. To ensure OpenLayers functions properly, I need to incorporate these technologies, even though I'm not very familiar with them. One key aspect of my proje ...

Enhancing Menu Visibility with PHP

Trying to use PHP to highlight the selected option CSS Code: ul.leftmenu { list-style-type: none; margin: 0; padding: 0; width: 100%; background-color: #ffffff; } ul.leftmenu li a { display: block; color: #2e3e49; padding ...

Stop images from flipping while CSS animation is in progress

I've been developing a rock paper scissors game where two images shake to mimic the hand motions of the game when a button is clicked. However, I'm facing an issue where one of the images flips horizontally during the animation and then flips bac ...

Sort data by checking either multiple or single checkbox options in AngularJS; if none are selected, display all results

My goal is to implement a filter in my AngularJS code that will filter data based on selected checkboxes. If no checkbox is selected, all results should be displayed without any filtering. Currently, the issue I am facing is that the data is only displayed ...

In Javascript, what significance does the symbol ":" hold?

While exploring the Ionic framework, I came across the following code snippet: import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: AlertController) { } I'm curious about the significanc ...

Troubleshooting: WordPress post not uploading to custom PHP file - Issue causing ERROR 500

Our website is built using WordPress, and I was tasked with adding a function to our newsletter subscription that sends an email to a specific address based on the selected value in the form. Everything was working perfectly on my local host, but when I tr ...

Locate the final element within an array using JavaScript

Provided with a file path like new/lib/java.exe, I am looking to eliminate the root folder 'new' and structure the new path as lib/java.exe. Challenge: After my attempts, I am left with the path as lib/java.exe/ which includes an unwanted "/". I ...

Tips for adding style to the first list element and first children using jQuery

Looking at the following markup: <ul> <li> // this <ul> <li> <div></div> </li> <li> <div></div> </li> </ul> </li> <li> ...