Explanation
I have searched around for this but was unable to find a solution and/or advice for this specific problem.
I have a navigation menu with items that have drop down lists. These drop down lists are enabled when any one of the menu buttons with a drop down is clicked, thereafter the drop downs show/hide on hover. If anywhere else on the screen is clicked whilst the drop downs are enabled then they immediately get disabled and disappear.
Sorry for the poor explanation, that is the best way I can put it 🙁
I have produced a basic example here (the drop downs dont show, they just log in the console):
Please ignore all HTML and CSS, the easiest way to create this was to just pile all the code in, it is not relevant for this issue.
My Question
As you can see I have a property called MN.dropDownsOn. This property is a boolean to indicate whether or not the drop downs should show on mouseenter. The boolean is enabled/disabled when a menu item is clicked, or anything but is clicked…
What I would like to know is whether this can be achieved in a better way? I dont really like storing a global value to indicate whether the drop downs are enabled or not, but I cannot think of a better way of doing it. Any suggestions?
Thanks in Advance
For ease of access, here is my JS:
MN.dropDownsOn = false;
/**
* Initialize the Drop Downs
* Initialize the Drop Downs in the Navigation Menu
*/
MN.initializeDropDowns = initializeDropDowns;
function initializeDropDowns(){
// THIS IS THE PART I AM UNSURE ABOUT
$(document).on('click','.dropdown',function(e){
// Enable all the drop downs
MN.dropDownsOn = true;
// Ensure this down is now visible
$(this).trigger('mouseenter');
// Stop jQuery from disabling the dropdowns
e.stopPropagation();
});
$(document).click(function(){
// Enable all the drop downs
MN.dropDownsOn = false;
});
// BELOW IS FINE, APART FROM THE MN.DROPDOWNSON MIGHT NEED TO GO
// Set the hover functions
$(document).on('mouseenter','.dropdown',function(){
if(MN.dropDownsOn){
// Show the dropdown
}
});
// Set the hover functions
$(document).on('mouseleave','.dropdown',function(){
if(MN.dropDownsOn){
// Hide the dropdown
}
});
}
As no other suggestions came through, I would put my comments as recommendations:
Make dropDownsOn a local variable in function initializeDropDowns. This will be available to all the event handlers being registered in the function.
Convert initializeDropDowns into a class and add the event handlers and dropDownsOn as member variables. The object constructed can be bound as data to $(document) and retrieved during event handling.