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);
Here is the error I got when running it in latest chrome in windows 11:
I think the error comes from this line:
specifically from this part:
I believe that the
querySelectordid not find an element of that description in the HTML, and so returnednull. Therefore, when you try to take itsscrollWidth, you get an error.