To make this menu work, you need to push the website to the right when a user clicks the button for the first time.
When the user clicks the button for a second time, you push the website back to the left.
In short, you need to:
Add an event listener to the button.
Push screen to the right when button gets clicked.
Push screen back when button gets clicked again.
Adding the event listener
First, we need to select the button with JavaScript. We can do this with querySelector.
const button = document.querySelector('button')
Then, we add an event listener with addEventListener.
button.addEventListener('click', event => {
console.log('push the screen!')
})
Pushing the screen
To push the screen to the right, we need to push BOTH .offsite-container and .site-container to the right. The best way to push stuff around in CSS is to use the transform property.
We don’t want to push the containers when the website gets loaded. We only want to push the containers when the button is clicked.
The easiest way to tell whether the menu should be open is to add a class to <body>. If the class is present, we need to open the menu. Let’s call this class offsite-is-open.
When the button gets clicked for the second time, you want to push the screen back to the left. To do this, you remove offsite-is-open from <body>.
Here’s how to do it:
Check whether <body> has the offsite-is-open class.
If it has the class, remove the class.
If it does not have the class, add the class.
We can check whether <body> has offsite-is-open with an if statement.
button.addEventListener('click', event => {
if (body.classList.contains('offsite-is-open')) {
// Remove .offsite-is-open to close the menu
} else {
// Add .offsite-is-open to open the menu
}
})
We can then add/remove the class with classList.add and classList.remove.