Skip to content
Advertisement

How to handle event element in container?

I want to click btnToggle, Navigation will run but I don’t know why this code sometimes is successful, sometimes is unsuccessful.

Help me please, thanks all

JavaScript
JavaScript

Advertisement

Answer

You’re pretty close. Because you attached the event listener to document, your callback function will actually run if you click anywhere on the page. And because browsers have something called event bubbling, that might be the cause of your inconsistencies.

Instead, you should put the event listener on the button only. I would do it like this:

JavaScript

Here, I extracted the moveNavRight out to a separate function for a bit more clarity. So how this code would work is: if you click on btnToggle, the nav will move to right 0. But if you click on the page/document anywhere else, then the nav will move to right -100%.

Hope this is what you were looking for!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement