Web accessible navigation - javascript

I'm stuck while implementing drop down for each individual list item on focus/hover on any of them, now on hovering over any single list item all dropdowns are getting displayed.
This is my pen: https://codepen.io/apeandme/pen/GRZOxJQ
and the JS:
// main navigation interaction
'use strict';
var navbar;
var triggerContainer;
var triggerLink;
var toggleButton;
var lastMenuItem;
var mouseOutTimer; // timer used to delay hiding of menu after mouse leaves
var mouseOutHideDelay = 0; // time (in ms) before menu is closed after mouse leaves
var menuVisible = false;
var i = 0;
window.addEventListener('DOMContentLoaded', function(e) {
navbar = document.querySelector('nav');
triggerContainer = document.querySelectorAll('nav > ul > li.with-dd');
triggerLink = document.querySelectorAll('nav > ul > li.with-dd > a');
toggleButton = document.querySelectorAll('nav > ul > li.with-dd > .toggle-button');
lastMenuItem = document.querySelectorAll('nav > ul > li.with-dd > ul > li:last-of-type > a');
// Show the menu on mouse hover of the trigger
triggerContainer.forEach(item => {
item.addEventListener('mouseover', function(e) {
showMenu();
clearTimeout(mouseOutTimer);
});
});
// Hide the menu when mouse hover leaves both the trigger and menu fly-out, but only after a short delay to help people jerky mouse movements (like those using head/eye trackers)
triggerContainer.forEach(item => {
item.addEventListener('mouseout', function(e) {
mouseOutTimer = setTimeout(function() {
hideMenu();
}, mouseOutHideDelay);
});
});
// Hide the menu when the user tabs out of it
triggerContainer.forEach(item => {
item.addEventListener('keydown', triggerKeydownHandler);
});
// Toggle the menu when the trigger is activated
toggleButton.forEach(item => {
item.addEventListener('click', toggleMenu);
});
// Close the menu when the user activates something outside the navbar.
document.body.addEventListener('click', handleBodyClick);
});
/**
Menu visibility
**/
function showMenu() {
triggerLink.forEach(item => {
item.setAttribute('aria-expanded', true);
});
toggleButton.forEach(item => {
item.setAttribute('aria-expanded', true);
});
menuVisible = true;
}
function hideMenu() {
triggerLink.forEach(item => {
item.setAttribute('aria-expanded', false);
});
toggleButton.forEach(item => {
item.setAttribute('aria-expanded', false);
});
menuVisible = false;
}
function toggleMenu() {
if (menuVisible) {
hideMenu();
} else {
showMenu();
}
}
/**
Event handlers
*/
function handleBodyClick(e) {
if (!navbar.contains(e.target)) {
hideMenu();
}
}
function triggerKeydownHandler(e) {
// Hide the menu a keyboard user tabs out of it or presses Escape
if ((e.key === 'Tab' && !e.shiftKey && e.target === lastMenuItem) || e.key == 'Escape') {
hideMenu();
// Move focus back to the menu toggle button if Escape was pressed
if (e.key == 'Escape') {
toggleButton.focus();
}
}
}

Instead of opening all the dropdowns at once when one is hovered, you need to pass the 'hover' event to the function, in order to know which one of the triggers were hovered :
triggerContainer.forEach((item) => {
item.addEventListener("mouseover", function (event) { // catch the 'hover' event
showMenu(event); // pass the event to your function
clearTimeout(mouseOutTimer);
});
});
function showMenu(event) {
event.target.setAttribute("aria-expanded", true); // know which element whas hovered
event.target.nextElementSibling.setAttribute("aria-expanded", true); // open the corresponding dropdown
menuVisible = true;
}

Thanks for the help. Have changed the code , for both showMenu and hideMenu and for mouseover and mouseout events, now individual drop downs are showing on hovering over single menu item, but the dropdowns are hiding soon enough I'm reaching to the last menu item inside the dropdown. Am I missing anything and currently this error is in the console whenever hovering over the last menu item inside the drop-down-
Uncaught TypeError: Cannot read property 'setAttribute' of null
at hideMenu (main.js:68)
at main.js:38
//main navigation interaction
"use strict";
var navbar;
var triggerContainer;
var triggerLink;
var toggleButton;
var lastMenuItem;
var mouseOutTimer; // timer used to delay hiding of menu after mouse leaves
var mouseOutHideDelay = 1000; // time (in ms) before menu is closed after mouse leaves
var menuVisible = false;
window.addEventListener("DOMContentLoaded", function (e) {
navbar = document.querySelector("nav");
triggerContainer = document.querySelectorAll("nav > ul > li.with-dd");
triggerLink = document.querySelectorAll("nav > ul > li.with-dd > a");
toggleButton = document.querySelectorAll(
"nav > ul > li.with-dd > .toggle-button"
);
lastMenuItem = document.querySelectorAll(
"nav > ul > li.with-dd > ul > li:last-of-type > a"
);
// Show the menu on mouse hover of the trigger
triggerContainer.forEach((item) => {
item.addEventListener("mouseover", function (e) {
showMenu(e);
clearTimeout(mouseOutTimer);
});
});
// Hide the menu when mouse hover leaves both the trigger and menu fly-out, but only after a short delay to help people jerky mouse movements (like those using head/eye trackers)
triggerContainer.forEach((item) => {
item.addEventListener("mouseout", function (e) {
mouseOutTimer = setTimeout(function () {
hideMenu(e);
}, mouseOutHideDelay);
});
});
// Hide the menu when the user tabs out of it
triggerContainer.forEach((item) => {
item.addEventListener("keydown", triggerKeydownHandler);
});
// Toggle the menu when the trigger is activated
toggleButton.forEach((item) => {
item.addEventListener("click", toggleMenu);
});
// Close the menu when the user activates something outside the navbar.
document.body.addEventListener("click", handleBodyClick);
});
/**
Menu visibility
**/
function showMenu(e) {
e.target.setAttribute("aria-expanded", true);
e.target.nextElementSibling.setAttribute("aria-expanded", true);
menuVisible = true;
}
function hideMenu(e) {
e.target.setAttribute("aria-expanded", false);
e.target.nextElementSibling.setAttribute("aria-expanded", false);
menuVisible = false;
}
function toggleMenu() {
if (menuVisible) {
hideMenu(e);
} else {
showMenu(e);
}
}
/**
Event handlers
*/
function handleBodyClick(e) {
if (!navbar.contains(e.target)) {
hideMenu();
}
}
function triggerKeydownHandler(e) {
// Hide the menu a keyboard user tabs out of it or presses Escape
if (
(e.key === "Tab" && !e.shiftKey && e.target === lastMenuItem) ||
e.key == "Escape"
) {
hideMenu();
// Move focus back to the menu toggle button if Escape was pressed
if (e.key == "Escape") {
toggleButton.focus();
}
}
}

Related

How do i toggle something on click using an event listener if condition is met?

I want to toggle a navbar on click using a button and if the navbar is already active I want to disable it when the user clicks anywhere. The event listeners are all connected and the toggling code works normally but implementing the "click anywhere on the screen to turn off" feature isn't working.
Edit: I can now toggle by clicking anywhere but I can't toggle using the button I can only turn it on and not off.
const button = document.querySelector('button.mobile-menu-button');
const menu = document.querySelector('.mobile-menu');
let menuActive = false;
button.addEventListener('click', (e) => {
e.stopPropagation();
if (!menuActive) {
menu.classList.toggle('hidden');
menuActive = true;
}
});
window.addEventListener('click', () => {
if (menuActive) {
menu.classList.toggle('hidden');
menuActive = false;
}
});
The problem is that when you click on the button, you are also clicking on the window at the same time. You should use stopProgopation().
Here is a solution. When the button is clicked, the menu gets shown. If the user then clicks on the screen somewhere else other than the button, the menu will disappear.
<div id="menu" class="mobile-menu hidden">This is the menu</div>
<button class="mobile-menu-button">Button</button>
<script>
const button = document.querySelector('button.mobile-menu-button');
const menu = document.getElementById('menu');
let menuActive = false;
button.addEventListener('click', (e) => {
e.stopPropagation();
if (!menuActive) {
menu.classList.toggle('hidden');
menuActive = true;
}
});
window.addEventListener('click', () => {
if (menuActive) {
menu.classList.toggle('hidden');
menuActive = false;
}
});
</script>
<style>
.mobile-menu {
display: block;
}
.hidden {
display: none;
}
</style>
I found I didn't need a condition for the button itself, only the window. Thanks to everyone for helping.
const button = document.querySelector('button.mobile-menu-button');
const menu = document.querySelector('.mobile-menu');
let menuActive = false;
button.addEventListener('click', (e) => {
e.stopPropagation()
menu.classList.toggle('hidden');
menuActive = true;
});
window.addEventListener('click', () => {
if (menuActive) {
menu.classList.toggle('hidden');
menuActive = false;
}
});

JavaScript preventDefault is delayed/not working when app is deployed on a network

I have an application with custom context menus that are displayed on right-click. When that happens, I don't want default windows menu to appear. I use the following code to accomplish that:
// right click
if (e.which == 3) {
let menuVisible = false;
const toggleMenu = command => {
menu.style.display = command === "show" ? "block" : "none";
menuVisible = !menuVisible;
};
const setPosition = ({ top, left }) => {
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
toggleMenu("show");
};
const origin = {
left: e.pageX,
top: e.pageY
};
setPosition(origin);
// toggle right clicked menu visibility
window.addEventListener("click", e => {
if (menuVisible) toggleMenu("hide");
});
// Set up an event handler for the document right click
document.addEventListener("contextmenu", function (event) {
// Only do something when the element that was actually right-clicked
if (event.target.classList.contains("menu")) {
event.preventDefault();
}
});
}
When app is running on localhost everything works as expected.
However, when application is deployed on a network server and then accessed from any clients on the network the default menu appears first and then custom menu displayed behind it. There are no any errors.
Any advise on how to fix that will be greatly appreciated.
Update: It seems that if right mouse button is hold not just clicked the behavior is as expected.
I think you'll have to do something like this:
let menuVisible = false;
const toggleMenu = command => {
menu.style.display = command === "show" ? "block" : "none";
menuVisible = !menuVisible;
};
const setPosition = ({ top, left }) => {
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
};
// Set up an event handler for the document right click
document.addEventListener("contextmenu", function (e) {
if (e.target.classList.contains("menu")) {
e.preventDefault();
setPosition({
left: e.pageX,
top: e.pageY
});
toggleMenu("show");
}
});
// Hide menu
document.addEventListener("click", function(e) {
if (e.target.classList.contains("menu-item")) {
alert("menu item was clicked");
}
toggleMenu("hide");
});
#menu {
position: absolute;
padding: 10px;
background: #eee;
list-style-type: none;
}
<ul id="menu" style="display:none;">
<li class="menu-item">Item 1</li>
<li class="menu-item">Item 2</li>
<li class="menu-item">Item 3</li>
</ul>
<button class="menu">toggle menu on right click</button>

Disabling prevent.Default action

I have a piece of javascript code which initiates mobile menu dropdown. But while I was working on this, I wasn't paying attention and stupidly copied a code from another source and now I can't click on parent items on mobile menu.
When I remove e.preventDefault();, I'm getting an error in console and menu is not working. Here is the full code. What can I do with my code to make the parent items clickable?
var $dropdownOpener = $('.mobile-header-navigation .menu-item-has-children > a');
if ($dropdownOpener.length) {
$dropdownOpener.each(function () {
var $thisItem = $(this);
$thisItem.on('tap click', function (e) {
e.preventDefault();
var $thisItemParent = $thisItem.parent(),
$thisItemParentSiblingsWithDrop = $thisItemParent.siblings('.menu-item-has-children');
if ($thisItemParent.hasClass('menu-item-has-children')) {
var $submenu = $thisItemParent.find('ul.sub-menu').first();
if ($submenu.is(':visible')) {
$submenu.slideUp(450);
$thisItemParent.removeClass('qodef--opened');
} else {
$thisItemParent.addClass('qodef--opened');
if ($thisItemParentSiblingsWithDrop.length === 0) {
$thisItemParent.find('.sub-menu').slideUp(400, function () {
$submenu.slideDown(400);
});
} else {
$thisItemParent.siblings().removeClass('qodef--opened').find('.sub-menu').slideUp(400, function () {
$submenu.slideDown(400);
});
}
}
}
});
});
}
}
Maybe try to call e.originalEvent.preventDefault() with null checks like :
e && e.originalEvent && e.originalEvent.preventDefault()

How to toggle the class

Hi folks i am having problem to execute this code in the browser onclick event on an icon when i click it it works fine when i click to close the list it close and open again like on the mouse down it close and then releasing the button it open again here is the function code where i am doing wrong
toggleExpand(e, focus = true) {
this.moving = true;
if (e) {
e.preventDefault();
e.stopPropagation();
}
this.expanded = !this.expanded;
toggleClass(this.config.open, this.el);
ariaToggle('opened', this.current);
if (!this.selected) {
toggleClass(this.config.icons.expanded, this.icon);
}
if (this.expanded) {
this.select();
console.log('Clicked1');
if (this.params.scrollToView) {
this.el.parentElement.previousElementSibling.scrollIntoView();
}
} else {
this.current.setAttribute('tabindex', 0);
console.log('Clicked2');
if (focus) {
this.current.focus();
}
}
setTimeout(() => {
this.moving = false;
}, 100);
}
i put the console to check it on 1st click i get clicked1 on on 2nd i get clicked2 and instantly clicked1 again how to stop it here without css.

Closing toggle menu not working properly with JQuery code

I am working on closing toggle menu for mobiles and having a small problem. So what i want is when the toggle menu is active, user to be able to close it by touching somewhere on the screen on his device. I almost got it working, but when closed the basket in the header disappears and the menu doesn't retrieve to a hamburger icon. I am working on Wordpress website, just to notice.
I guess the problem comes from this: aria-expanded="true" , because the default value should be false after the user has closed it.
So my website is:
https://www.ngraveme.com/bg
my JQuery code is:
jQuery(document).ready(function($) {
var $menu = $('.menu');
$('.menu-toggle').click(function() {
$menu.toggle();
});
$(document).mouseup(function(e) {
if (!$menu.is(e.target) // if the target of the click isn't the container...
&&
$menu.has(e.target).length === 0) // ... nor a descendant of the container
{
$menu.hide();
}
});
});
and the original js code written from the theme i am using in wordpress is:
/**
* navigation.js
*
* Handles toggling the navigation menu for small screens.
* Also adds a focus class to parent li's for accessibility.
* Finally adds a class required to reveal the search in the handheld footer bar.
*/
(function() {
// Wait for DOM to be ready.
document.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('site-navigation');
if (!container) {
return;
}
var button = container.querySelector('button');
if (!button) {
return;
}
var menu = container.querySelector('ul');
// Hide menu toggle button if menu is empty and return early.
if (!menu) {
button.style.display = 'none';
return;
}
button.setAttribute('aria-expanded', 'false');
menu.setAttribute('aria-expanded', 'false');
menu.classList.add('nav-menu');
button.addEventListener('click', function() {
container.classList.toggle('toggled');
var expanded = container.classList.contains('toggled') ? 'true' : 'false';
button.setAttribute('aria-expanded', expanded);
menu.setAttribute('aria-expanded', expanded);
});
// Add class to footer search when clicked.
document.querySelectorAll('.storefront-handheld-footer-bar .search > a').forEach(function(anchor) {
anchor.addEventListener('click', function(event) {
anchor.parentElement.classList.toggle('active');
event.preventDefault();
});
});
// Add focus class to parents of sub-menu anchors.
document.querySelectorAll('.site-header .menu-item > a, .site-header .page_item > a, .site-header-cart a').forEach(function(anchor) {
var li = anchor.parentNode;
anchor.addEventListener('focus', function() {
li.classList.add('focus');
});
anchor.addEventListener('blur', function() {
li.classList.remove('focus');
});
});
// Add an identifying class to dropdowns when on a touch device
// This is required to switch the dropdown hiding method from a negative `left` value to `display: none`.
if (('ontouchstart' in window || navigator.maxTouchPoints) && window.innerWidth > 767) {
document.querySelectorAll('.site-header ul ul, .site-header-cart .widget_shopping_cart').forEach(function(element) {
element.classList.add('sub-menu--is-touch-device');
});
}
});
})();
Try replacing your jQuery code with this:
jQuery(document).ready(function($) {
$(document).mouseup(function(e) {
var $menuContainer = $('.menu');
var $menu = $menu.find('ul');
var $container = $('.site-navigation');
var $button = $container.find('button')
if (!$menuContainer.is(e.target) && $menuContainer.has(e.target).length === 0) {
if ($container.hasClass('toggled')) {
$button.attr('aria-expanded', false);
$menu.attr('aria-expanded', false);
}
}
});
});
It uses the vanilla-js code from the template for hiding/showing the menu, but with jQuery synthax.

Categories

Resources