4

I have a menu which is hidden by default and should display after clicking on a button - no problem.

The problem starts when I want to hide the menu again - when I hide it by clicking away on the page, it's ok. However, when I want to hide it by clicking on the yellow button, it hides but after clicking on Normal text it displays again. I don't know the reason but that's certainly something I don't want.

function zobrazSkryVseobecne(idecko) {
    var miesto = document.getElementById(idecko);
    miesto.className = (miesto.className === "skryt" ? "" : "skryt");
}

Here's my whole code: https://jsfiddle.net/tu958pwg/

Thanks in advance for any advice and sorry for my bad English.

2 Answers2

0

Ok, so, I have found that the problem is in onfocusout event. The main problem I think it is that you are using that event in a not allowed element Check this info about onfocusout event and the elements where you can use it.

I know this is not a solution, but a guide for you to think about the solution yourself.

Let me know if I can help you in any other way.

Richard Fazzi
  • 433
  • 3
  • 9
0

This is because when you click on the menu button once (show the dropdown), then again (hide the dropdown), the menu button still has focus. So when you click on "normal text" (or anywhere else in the window) and menu loses focus, onfocusout fires, which shows the dropdown.

A better approach might be to add and clear an event listener for onfocusout:

function hideElem() {
  var miesto = document.getElementById('hidden');
  miesto.className = 'skryt';
}


function zobrazSkryVseobecne(idecko) {
  var miesto = document.getElementById(idecko);
  var menu = document.getElementById('menu');
  // If hidden
  if (miesto.className === 'skryt') {
    miesto.className = '';
    menu.addEventListener('focusout', hideElem)
  // Else if shown
  } else {
    miesto.className = 'skryt';
    menu.removeEventListener('focusout', hideElem)
  }
}

And be sure to remove onfocusout="zobrazSkryVseobecne('hidden')" from your button.

sallf
  • 2,583
  • 3
  • 19
  • 24