JS SOLUTION: mobile menu touch to close + close on tablet orientation change

Hello,

Hope this is allowed in this forum as I have never seen anyone paste Javascript in a post. Please delete if it is not appropriate.

I thought I’d share the below JQuery / Javascript. I am running these snippets of code using the ‘Simple CSS + JS wordpress’ plugin - you just copy and paste into the ‘Custom JS’ section. There seem to be no issues or conflicts. These lines of code ensure the .open-responsive menu closes when a user touches the screen at any point outside of the drop down menu itself, as well as ensure the dropdown menu auto closes when a mobile or tablet changes orientation.

These are both topics that are frequently brought up in this forum. Both issues cannot be resolved through CSS, and I’m yet to find a plugin that fixes them.

/* Closes .open-responsive-menu drop down menu when a user touches or mouse clicks outside of the drop down menu itself or via the ham burger icon */

jQuery(document).ready(function( $ ){
$(document).on(“click touchend”, function(event){
var $trigger = $(".responsive-menu");
var $menu = $(".open-responsive-menu");
if(($trigger !== event.target && !$trigger.has(event.target).length) && ($menu !== event.target && !$menu.has(event.target).length)){
$(".responsive-menu").fadeOut(300);
}
});

});

/* Close .open-responsive-menu mobile menu drop down when a user changes the orientation of a mobile or tablet */

window.addEventListener(“orientationchange”, function() {
if(jQuery(“nav.responsive-menu”).hasClass(“active”)){
jQuery(".open-responsive-menu").trigger(“click”)
}
}, false);

Hey there

Well, thank you for sharing your solution, such topics are very welcome :slight_smile: