Jquery Scroll to Top

I have successfully created a scroll to top and scroll to bottom feature using jquery. The scrolling is based on percentages, so if it scrolls from top to bottom at 50%, it will stop at 50%. Now, I am trying to figure out how to make the remaining 50% of the scroll happen when clicked again. Does anyone have any suggestions or ideas on how to accomplish this with jquery?

For reference, here is the fiddle: http://jsfiddle.net/TkYpY/

Thank you, vicky

Answer №1

$('#btnScrollTop').on("click", function () {
var percentageToScroll = 50;
var percentage = percentageToScroll / 100;
var totalHeight = $(document).height() - $(window).height();
if(scrollPosition > 0 )
{
scrollPosition = scrollPosition - (totalHeight * percentage);
}

console.log('scrollPosition: ' + scrollPosition);
$('html,body').animate({
    scrollTop: scrollPosition
}, 'slow', function () {
    console.log("reached top");
});

});

var scrollPosition = 0;
$('#btnScrollBottom').on("click", function () {
var percentageToScroll = 50;
var percentage = percentageToScroll / 100;
var totalHeight = $(document).height() - $(window).height();

 if(   scrollPosition < totalHeight)
 {
scrollPosition = scrollPosition + totalHeight * percentage;
 }
console.log('scrollPosition: ' + scrollPosition);
jQuery("html, body").animate({
    scrollTop: scrollPosition
}, 900);
});

Answer №2

The second click won't cause the page to scroll further since you've already reached the scrollAmount limit.

To continue scrolling beyond that point, define a variable called scrollAmount outside the function. Then, when clicking on the bottom link again, calculate the next scroll Amount while ensuring it doesn't exceed the document height limit. Add this new amount to the globally declared scrollAmount variable.

Answer №3

$('#headerTop').on("click", function () {
var scrollPercentage = 75;
var percentage = scrollPercentage / 100;
var currentHeight = $(document).scrollTop();
var distanceToScroll = currentHeight * (1 - percentage);

console.log('distanceToScroll: ' + distanceToScroll);
$('html,body').animate({
    scrollTop: distanceToScroll
}, 'slow', function () {
    console.log("reached the top");
});

});

var totalScrollAmount = 0;
$('#headerBottom').on("click", function () {
var scrollPercent = 45;
var percentage = scrollPercent / 100;
var fullHeight = $(document).height() - $(window).height();
totalScrollAmount = totalScrollAmount + fullHeight * percentage;
console.log('totalScrollAmount: ' + totalScrollAmount);
jQuery("html, body").animate({
    scrollTop: totalScrollAmount
}, 900);
});

Answer №4

I made some changes to your code on the fiddle. It seems like there might be a calculation issue. You can find the modified fiddle here. Does this solution meet your requirements?

To start, create a global variable called height with a default value.

In the scroll function at the top, replace

var height = $(document).scrollTop();
with
height -= $(document).height() - $(window).height();

Then, in the bottom scroll function, replace

var height = $(document).height() - $(window).height();
with
height += $(document).height() - $(window).height();
.

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

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...

Next.JS: The Key to Long-Term Data Storage

How can we retrieve and maintain data during app initialization or user login so that it persists throughout the application? Currently, every time a page is refreshed, the context is cleared and attempting to use getServerSideProps results in undefined ...

Verifying user input with JQuery's $.post function

I have a question regarding asynchronous calls. My goal is to validate whether a given "code" is valid without refreshing the page. Here's the scenario in brief: I need to determine if a variable should be set to true or false based on the response ...

PHP Pagination Made Easy

Currently, I am developing a website focused on HIV prevention information warehousing. Numerous collaborators will be contributing articles using a tinyMCE GUI. The design team is keen on having control over page lengths. They are interested in implement ...

Efficiently loading Angular views with lazy loading techniques

I am currently working on a calculator website powered by Angular. This single-page site is fully responsive and divided into 7 sections, each featuring different calculators based on user preferences. To improve loading time, I am interested in implementi ...

Converting HTML to plain text on an Android device

I need help converting HTML text to plain text and displaying it in a TextView. However, I am encountering an issue where additional paragraphs are being added after the conversion. Please refer to the image https://i.sstatic.net/SxSf0.jpg Can someone exp ...

How To Make Divs Flow Smoothly With CSS

Here is the code snippet I am working with: /* Coded by @fitri This ReactJS project component was created with love https://codepen.io/fitri/full/oWovYj/ */ function enableDragSort(listClass) { const sortableLists = document.getElementsByClassNa ...

Transforming PHP Associative array into JSON object causes issues with malformed JSON when spaces are present in the values

In PHP, I generate an array and then convert it to JSON format. This JSON data is processed with an onclick event and sent to another file using AJAX. The issue arises when some values in the PHP array contain spaces, causing the JSON object to break and ...

How to implement pagination with subdocuments in Node.js using Mongoose

My attempt to paginate a subcomment named "Items" within a collection using mongoose-paginate-v2 has not been successful. Below is my model: const mongoosePaginate = require('mongoose-paginate-v2'); const PettyCashItemsSchema = ...

requesting data from the server

When trying to access the Coursera API on the client side, I encountered an issue with CORS blocking the request. JSONP was not a viable solution because the API is returning JSON data. My experience lies mainly in client-side development, so I am unsure ...

Populate the database with values when the button is clicked

Hello, I encountered an issue with my code where it is adding empty values to the database when attempting to enter input text values. I am using PHP and MySQL for this task. <html> <body> <input type="text" name="value" /> <input ...

What is the best way to style output in jQuery for a specific div?

I have developed a tool for creating forms, but I am struggling to format the output neatly like pretty print. I have tried using \n and pre tags as well. allCont += "<label>"+insCleaned+"</label><input type='text' name= ...

Passing a ref from a parent component to a child component in reactjs

I have the following situation, how can I make sure that the attachment field in the child component is accessible from the parent component? class ServiceDeskCustomerCreate extends Component { constructor(props, context) { super(props, context); ...

Which event listener in the DOM API should I use to trigger an action when a form field is focused, whether through a mouse click or by tabbing?

My aim is to increase the size of form fields when the cursor focuses on them, either through a mouse click or by tabbing using the keyboard. By utilizing document.activeElement focus, I can identify when the user clicks inside a text input or selects an ...

Adsense ad unit is not responsive and fails to display properly at dimensions of 320x50 px

I have a unique banner ad that I want to display as the footer on my responsive website. Using media queries recommended in the advertising documentation, I am adjusting the size based on different screen widths. Check out the CSS code below: <style&g ...

1. "Customizing Navbar height and implementing hover color for links"2. "Tips for

Having issues adjusting the height of my Navbar - when I try to do so, the collapse button doesn't function properly. I've attempted setting the height using style="height: 60px;" and .navbar {height: 60px;} but the collapse menu stops ...

Error in Java script due to the combination of Jmeter and Selenium APIs

While using Jmeter in conjunction with Selenium WebDriver, I encountered an unhandled error "016/02/17 16:51:47 ERROR - com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler: :14:94 Expected , but found ; WDS.browser.findElement(pkg.By.cssSele ...

What could be causing a syntax error when I use `npm run start` with npm react-scripts?

After months of working on a full stack React app, I encountered an unexpected error when trying to run npm run start from the command line. The error message was as follows: // npm run start > [email protected] start /Users/eden/Documents/GitH ...

Console-based Controller Object Property Updates

Is it possible to test content containing an ng-if by updating a property on the controller's variable in the console? <div class="manager-only" ng-if="teamSchedule.userObject.isManager"> <a href="#add-game"> <input class=" ...

Could someone help with why the target id is not being properly passed when clicking on a li

Currently, I am working on a ReactJS project utilizing MaterialUI. The code snippet I am dealing with is as follows: { this.state.categories.map((category, key) => ( <List> <ListItem button id={key} onClick={this.handleClick}> ...