Dohn Joe
Dohn Joe

Reputation: 23

"body" overflow hidden or scroll via onclick function

I have a dropdown menu which covers the whole page if opened (100vh + 100 vw) and I try to disable the scrolling of the body when I click the dropdown menu button.

Adding and removing a class on click didn't worked for me for some reason but adding directly a style worked for me perfectly via: <a href="#" onclick="document.body.style.overflow = 'hidden';>

But by clicking the link again doesn't set the overflow to scroll again, so is anyone able to help me out please?

Upvotes: 0

Views: 4058

Answers (1)

LeonNikolai
LeonNikolai

Reputation: 112

Two problems, you are not removing the styling after its already 'hidden', and you missed a quotation mark at the end of onclick. The bellow code will check if the body overflow is hidden or not before changing between them.

<a href="#" onclick="document.body.style.overflow = document.body.style.overflow == 'hidden' ? 'auto' : 'hidden' "/>

i would also suggest using a button insted of a a element when used to run javascript.

<button onclick="document.body.style.overflow = document.body.style.overflow == 'hidden' ? 'auto' : 'hidden' "/>

If you are looking for toggling a class, this should work. Where mystyle is the classname of the class you are toggling.

<button onclick="document.body.classList.toggle('mystyle')"/>

If toggling a class does not work, you have a specificity problem where other css styling applies over the "toggled class", you can check this via the element tab in developer tools.

Upvotes: 1

Related Questions