NeuroAgent

jQuery Smooth Scroll to Bottom on Click - Complete Guide

Learn how to implement smooth scroll animations with jQuery when clicking input elements. Complete code examples and customization options for optimal user experience.

Question

How to implement a smooth scroll animation to the bottom of the page when clicking an input element using jQuery?

I have an input element:

html
<input type="text" class="textfield" value="" id="subject" name="subject">

When the user clicks on this input, I want the page to smoothly scroll to the last element on the page, which is a submit button:

html
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">

The animation should be fluid and not too fast. I’m using the latest jQuery version and prefer to use default jQuery features without installing any plugins.

NeuroAgent

To implement a smooth scroll animation to the bottom of the page when clicking an input element using jQuery, you can use the animate() method combined with scrollTop() to create a fluid scrolling effect. The simplest approach involves targeting the submit button’s position and animating the window’s scroll position to that location with a duration of 800-1000 milliseconds for optimal user experience.

Contents

Basic jQuery Implementation

The most straightforward way to achieve smooth scrolling is by using jQuery’s animate() method. Here’s the basic implementation:

javascript
$(document).ready(function() {
    $('#subject').click(function() {
        // Calculate the position of the submit button
        var submitPosition = $('#submit').offset().top;
        
        // Smooth scroll to the submit button
        $('html, body').animate({
            scrollTop: submitPosition
        }, 1000); // 1000ms = 1 second animation
    });
});

This code works by:

  1. Detecting clicks on the input element with #subject
  2. Getting the vertical position of the submit button using offset().top
  3. Animating the scroll position of both html and body elements
  4. Setting a 1-second duration for smooth animation

Important note: Targeting both html and body ensures cross-browser compatibility, as different browsers may handle scrolling differently.

Alternative Scroll Methods

Method 1: Using scrollTop with window height

If you want to scroll to the bottom of the page rather than a specific element:

javascript
$(document).ready(function() {
    $('#subject').click(function() {
        $('html, body').animate({
            scrollTop: $(document).height() - $(window).height()
        }, 1000);
    });
});

Method 2: Using CSS scroll-behavior (jQuery-free approach)

For a simpler implementation without jQuery, you can use CSS:

css
html {
    scroll-behavior: smooth;
}

/* Then use simple JavaScript */
document.getElementById('subject').addEventListener('click', function() {
    document.getElementById('submit').scrollIntoView({ behavior: 'smooth' });
});

However, since you specifically requested jQuery, we’ll focus on jQuery-based solutions.

Customization Options

Animation Duration Control

You can easily adjust the speed of the animation:

javascript
$(document).ready(function() {
    $('#subject').click(function() {
        var submitPosition = $('#submit').offset().top;
        var animationDuration = 1500; // 1.5 seconds
        
        $('html, body').animate({
            scrollTop: submitPosition
        }, animationDuration);
    });
});

Easing Functions

jQuery supports different easing functions for more natural motion:

javascript
$(document).ready(function() {
    $('#subject').click(function() {
        var submitPosition = $('#submit').offset().top;
        
        $('html, body').animate({
            scrollTop: submitPosition
        }, {
            duration: 1000,
            easing: 'swing' // or 'linear'
        });
    });
});

Common easing options:

  • swing (default) - slower at start and end
  • linear - constant speed throughout

Offset Adjustment

If you want to stop scrolling before reaching the exact button position:

javascript
$(document).ready(function() {
    $('#subject').click(function() {
        var submitPosition = $('#submit').offset().top - 50; // 50px offset
        
        $('html, body').animate({
            scrollTop: submitPosition
        }, 1000);
    });
});

Complete Working Example

Here’s a complete HTML page with all the necessary code:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smooth Scroll Example</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
        }
        
        .textfield {
            padding: 10px;
            margin: 20px 0;
            border: 2px solid #ddd;
            border-radius: 4px;
            width: 300px;
        }
        
        .submit {
            padding: 12px 24px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .submit:hover {
            background-color: #0056b3;
        }
        
        /* Add some content to make page scrollable */
        .content-section {
            height: 800px;
            margin: 20px 0;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #28a745;
            color: white;
            padding: 15px;
            border-radius: 4px;
            display: none;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <h1>Smooth Scroll Demo</h1>
    
    <p>Click on the input field below to smoothly scroll to the submit button at the bottom of the page.</p>
    
    <input type="text" class="textfield" value="" id="subject" name="subject" placeholder="Click me to scroll down">
    
    <!-- Content sections to make page scrollable -->
    <div class="content-section">
        <h2>Section 1</h2>
        <p>This is some content to make the page scrollable. The page contains multiple sections to demonstrate the smooth scroll functionality.</p>
    </div>
    
    <div class="content-section">
        <h2>Section 2</h2>
        <p>More content here. When you click the input field, the page will smoothly animate to the submit button.</p>
    </div>
    
    <div class="content-section">
        <h2>Section 3</h2>
        <p>Final content section before the submit button.</p>
    </div>
    
    <input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
    
    <div class="notification" id="scrollNotification">
        Scrolling to submit button...
    </div>
    
    <script>
        $(document).ready(function() {
            $('#subject').click(function() {
                // Show notification
                $('#scrollNotification').fadeIn().delay(2000).fadeOut();
                
                // Calculate the position of the submit button with some offset
                var submitPosition = $('#submit').offset().top - 100; // 100px offset from top
                
                // Smooth scroll to the submit button
                $('html, body').animate({
                    scrollTop: submitPosition
                }, 1000, 'swing'); // 1 second duration with swing easing
            });
            
            // Optional: Add click handler to submit button for feedback
            $('#submit').click(function() {
                alert('Form submitted successfully!');
            });
        });
    </script>
</body>
</html>

Best Practices and Considerations

Performance Optimization

  1. Debounce rapid clicks: Prevent multiple rapid scroll animations
javascript
$(document).ready(function() {
    var isScrolling = false;
    
    $('#subject').click(function() {
        if (isScrolling) return;
        
        isScrolling = true;
        var submitPosition = $('#submit').offset().top - 50;
        
        $('html, body').animate({
            scrollTop: submitPosition
        }, 1000, function() {
            isScrolling = false; // Reset after animation completes
        });
    });
});
  1. Use requestAnimationFrame for better performance (modern browsers)

Accessibility Considerations

  1. Ensure functionality works without JavaScript: Provide a regular link alternative
html
<a href="#submit" style="display: none;" id="skipLink">Skip to submit button</a>

<script>
$(document).ready(function() {
    $('#subject').click(function(e) {
        e.preventDefault();
        var submitPosition = $('#submit').offset().top - 50;
        $('html, body').animate({
            scrollTop: submitPosition
        }, 1000);
    });
});
</script>
  1. Add ARIA labels for screen readers:
html
<input type="text" class="textfield" value="" id="subject" name="subject" 
       aria-label="Subject field - click to scroll to submit button">

Mobile Considerations

  1. Touch events: Ensure smooth scrolling works on mobile devices
  2. Viewport handling: Consider mobile viewport restrictions

Error Handling

Add error handling for cases where the target element doesn’t exist:

javascript
$(document).ready(function() {
    $('#subject').click(function() {
        if ($('#submit').length === 0) {
            console.warn('Submit button not found');
            return;
        }
        
        var submitPosition = $('#submit').offset().top - 50;
        $('html, body').animate({
            scrollTop: submitPosition
        }, 1000);
    });
});

Advanced Customization

For more sophisticated animations, consider:

  1. ScrollTrigger-like behavior: Pause animation when user manually scrolls
  2. Parallax effects: Combine with other scroll-based animations
  3. Progress indicators: Show scroll progress with a visual indicator

Sources

  1. jQuery Documentation - animate()
  2. jQuery Documentation - scrollTop()
  3. jQuery Documentation - offset()
  4. MDN Web Docs - Smooth Scrolling
  5. CSS-Tricks - Smooth Scrolling

Conclusion

Implementing smooth scroll animations with jQuery is straightforward and provides excellent user experience. The key takeaways are:

  • Use $('html, body').animate({scrollTop: targetPosition}, duration) for smooth scrolling
  • Target both html and body elements for cross-browser compatibility
  • Adjust animation duration (800-1500ms) for optimal user experience
  • Consider adding offset values to prevent elements from being hidden behind fixed headers
  • Implement proper error handling and accessibility features
  • Test across different devices and browsers to ensure consistent behavior

For your specific use case with the input field and submit button, the basic implementation will work perfectly, and you can easily customize the animation speed and easing to match your website’s design aesthetic.