Onclick event doesn't work in first click, why?

I am trying to make an accordion menu. When the click to button i want to open the menu but it doesn’t work in first click. But after second or thirt click it working well. Seem like common issue for jr developer. I researched but nothing found. What is the problem.


u should attach ur code, so other people can check wheres the possible error… else would be hard to guess

1 Like

You attached the HTML but we can’t see your JS file, by my logic and no past work experience it seem like you are stuck at something called Event Bubbling and Capturing!
Which I would refer you to this amazing video:

Anyone more experienced feel free to correct me, please.

js codes is also in codepen.

I’m still not seeing the JS.

1 Like

Can you explain what you are expecting to happen when a user first clicks on the div with class="openMobileMenu" with respect to the expected movements of the menu?

You already asked a question related to checking the height of an element and were given a possible solution to check out. You still are attempting to check the height of the clickable element using style.height which will not work. I made a slight change to your if statement and it gets closer to what I think you want to achieve when first clicking on the icon.

1 Like

You are checking for inline styles on the elements before any inline styles have been set. HTMLElement.style returns the inline styles, not the styles you have set in the CSS file.

If you added the styles as inline styles to the elements you are checking the height property for your code (sort of) works.

I would suggest avoiding inline styles. Create classes that you can add/remove/toggle on the elements. You can also check if the classes are on the elements.

1 Like

Yes, that is the cause of the problem. To fix this I assigned a custom value to the height property and it works fine.
Everyone recommends me developer.mozilla.org but I’m learning from w3schools. should i learn from mdn?

You can use both.

I mainly use MDN, I think it has a higher standard and is still more professional than w3schools. For documentation, I’d suggest using MDN, but their learning sections are also pretty good.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.