Reputation: 31
I have a horizontal scrolling website that you drag by clicking and dragging with the cursor. On load the page should load in the middle of the scroll and you can drag it left and right.
It works when you refresh but if you go to another page and press back the "scroll the middle onLoad" JS doesn't work and neither does the click and drag JS.
Attempted to add unload handlers with no success. Any ideas?
// reload page to trigger JS after pressing back button
// firefox
function UnloadHandler() { window.removeEventListener('unload', UnloadHandler, false); }
window.addEventListener('unload', UnloadHandler, false);
//safari
window.addEventListener('pageshow', function (event) {
if (event.persisted) {
window.location.reload()
}
}, false);
// scroll to middle onLoad (horizontal, vertical)
document.querySelector('.home-container').scrollLeft = (document.querySelector('.home-container').scrollWidth - document.querySelector('.home-container').clientWidth) / 2
// enable click and drag
const slider = document.querySelector('.home-container');
let mouseDown = false;
let startX, scrollLeft;
let startDragging = function (e) {
mouseDown = true;
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
};
let stopDragging = function (event) {
mouseDown = false;
};
slider.addEventListener('mousemove', (e) => {
e.preventDefault();
if(!mouseDown) { return; }
const x = e.pageX - slider.offsetLeft;
const scroll = x - startX;
slider.scrollLeft = scrollLeft - scroll;
});
// Add the event listeners
slider.addEventListener('mousedown', startDragging, false);
slider.addEventListener('mouseup', stopDragging, false);
slider.addEventListener('mouseleave', stopDragging, false);
Upvotes: 2
Views: 475
Reputation: 565
Here is the error I got when running it in latest chrome in windows 11:
{
"message": "Uncaught TypeError: Cannot read properties of null (reading 'scrollWidth')",
"filename": "https://stacksnippets.net/js",
"lineno": 26,
"colno": 98
}
I think the error comes from this line:
document.querySelector('.home-container').scrollLeft = (document.querySelector('.home-container').scrollWidth - document.querySelector('.home-container').clientWidth) / 2
specifically from this part:
document.querySelector('.home-container').scrollWidth
I believe that the querySelector
did not find an element of that description in the HTML, and so returned null
. Therefore, when you try to take its scrollWidth
, you get an error.
Upvotes: 0