'Adding/removing classes to/from element scrolls page to the top?
I have to following code:
const burger = $("#burger-menu");
const main = $("#main");
const menu = $("#menu");
function showSideMenu() {
$("#menu").removeClass("hidden");
$("#main").addClass("blurry");
$("#main").addClass("fixed");
burger[0].childNodes[1].childNodes[1].classList.add("burger-top-animate");
burger[0].childNodes[1].childNodes[3].classList.add("burger-bottom-animate");
}
function hideSideMenu(event) {
$("#menu").addClass("hidden");
$("#main").removeClass("blurry");
$("#main").removeClass("fixed");
burger[0].childNodes[1].childNodes[1].classList.remove("burger-top-animate");
burger[0].childNodes[1].childNodes[3].classList.remove(
"burger-bottom-animate"
);
}
burger.click((event) => {
event.preventDefault();
if (menu.hasClass("hidden")) showSideMenu();
else hideSideMenu();
});
the burger click event handles a collapsing sidebar menu(hiding/showing). It behaves as expected, except it scrolls the page to the top. I can't explain to myself how that might be happening and I couldn't find the problem anywhere else.
The prevent default does not change as a thing.
Any help is appreciated!
Solution 1:[1]
The position:fixed
property added to the element causes these.
Consider programeticly setting the blur back on the selected element after pressing it using element.focus()
.
burger.click((event) => {
event.preventDefault();
if (menu.hasClass("hidden")) {
showSideMenu();
event.target.focus() //--added line
else hideSideMenu();
});
Haven't tested it myself.
Maybe wraping the focus statement in setTimeout, or menu.onfocus will be needed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lior bakalo |