Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A bookmarklet to scroll to the bottom of a webpage

i wonder if it is possible to create a bookmarklet to click on and the current webpage scrolls to the bottom!

javascript:function%20scrollme(){dh=document.body.scrollHeight;ch=document.body.clientHeight;if(dh>ch){moveme=dh-ch;window.scrollTo(0,moveme);}}

if i create a new bookmark and paste this as address nothing happens. I actually have no idea how to run javascript within a bookmarklet, however i just bookmarked the css-tricks Printliminator

maybe you could help, i would love to have a bookmarklet like this!

like image 315
matt Avatar asked Oct 30 '25 01:10

matt


2 Answers

First, your JavaScript only defines a function and does nothing else.

Second, you need to use document.documentElement (which represents the <html> element) instead of document.body:

javascript:dh=document.documentElement.scrollHeight;ch=document.documentElement.clientHeight;if(dh>ch){moveme=dh-ch;window.scrollTo(0,moveme);}

or, simply

javascript:window.scrollTo(0,document.documentElement.scrollHeight)

(apparently it doesn't matter if y-coord of window.scrollTo is greater than the maximum position).

Update: In case you have to deal with IE in quirks mode, the root element is indeed document.body. Other browsers let document.documentElement.clientHeight represent the document's height (see Finding the size of the browser window, which deals with the window's height, but contains a nice table). Anyway, you want to set the position of the scroller to whatever is the greatest of the three:

javascript:window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight))
like image 116
Marcel Korpel Avatar answered Nov 01 '25 17:11

Marcel Korpel


Here is a function that smoothly scrolls down to the bottom of a page:

function scroll(scroll_to) {
if (scroll.timer) clearTimeout(scroll.timer);
var scroll_current = document.body.scrollTop,
    distance = Math.abs(scroll_current - scroll_to);
if (scroll_current == scroll_to) return;
if (scroll_current > scroll_to) {
    if (distance < 5) {
        scroll_current -= distance;
    } else {
        scroll_current -= Math.ceil(distance / 10);
    }
}
if (scroll_current < scroll_to) {
    if (distance < 5) {
        scroll_current += distance;
    } else {
        scroll_current += Math.ceil(distance / 10);
    }
}
document.body.scrollTop = scroll_current;
scroll.timer = setTimeout(function() {
    scroll(scroll_to)
    }, 10);
}

If you call it:

scroll(document.body.scrollHeight - innerHeight);

it will scroll to the bottom of the page. You can also use it to scroll to the top of the page like this:

scroll(0);

Just attach it to a button or link's onclick event.

like image 33
Yaron Avatar answered Nov 01 '25 16:11

Yaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!