1

This is my menu bar
Closed:
enter image description here
Opened:
enter image description here

When window goes above a certain break point I want the menu bar to get closed. Here is the code:
html

<div class="d-md-none" id="menuButton">
                <input id="responsive-menu" type="checkbox" onchange="handleChange(this)">
                <label id="menuButtonMin" for="responsive-menu">
                <svg class="ham hamRotate ham4" viewBox="0 0 100 100" width="50" onclick="this.classList.toggle('active')">
                    <path class="line top" d="m 70,33 h -40 c 0,0 -8.5,-0.149796 -8.5,8.5 0,8.649796 8.5,8.5 8.5,8.5 h 20 v -20"></path>
                    <path class="line middle" d="m 70,50 h -40"></path>
                    <path class="line bottom" d="m 30,67 h 40 c 0,0 8.5,0.149796 8.5,-8.5 0,-8.649796 -8.5,-8.5 -8.5,-8.5 h -20 v 20"></path>
                </svg>
                </label>
            </div>

JS
window.addEventListener('resize', function(){
    const check = document.getElementById('responsive-menu');
    if(check.checked){
        if (window.innerWidth > 845){
            check.checked = false;
        }
    }
})

Even though in console, I see that check has a False value after a break point, the menu is still open. Any help please?

Aleksandre Bregadze
  • 199
  • 1
  • 3
  • 14

1 Answers1

1

changing the checked value won't trigger the onchange event. You must trigger it by yourself. After check.checked = false; add:

if ("createEvent" in document) {
  var evt = document.createEvent("HTMLEvents");
  evt.initEvent("change", false, true);
  check.dispatchEvent(evt);
}
else
  element.fireEvent("onchange");
Luca Corsini
  • 738
  • 4
  • 20
  • 2
    or `handleChange(check)` – epascarello Nov 09 '20 at 13:49
  • 1
    Huh that sounds interesting... But I still got an error: fireEvent is not a function – Aleksandre Bregadze Nov 09 '20 at 13:50
  • @AleksandreBregadze True, fireEvent is old stuff. I corrected it by using dispatchEvent. This way you'll use fireEvent only if your browser doesn't support event creation (I guess IE9 < ) – Luca Corsini Nov 09 '20 at 13:58
  • 1
    It does work nice! – Aleksandre Bregadze Nov 09 '20 at 14:03
  • However, now I have next issue, it does not change the state of label. After I resized the button still remained in "X" shape. Maybe anything for that too? – Aleksandre Bregadze Nov 09 '20 at 14:04
  • I just tried it, the X goes away correctly. var check = document.getElementById('responsive-menu'); if(check.checked){ if (window.innerWidth > 845){ check.checked = false; if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); check.dispatchEvent(evt); } else { element.fireEvent("onchange"); } } } Make sure to alter the .checked value BEFORE triggering the event – Luca Corsini Nov 09 '20 at 14:04