Handle dropdown's focus state - javascript

I am currently making a dropdown component in pure JavaScript. When the user click on the dropdown toggle, the content gain focus and its content is being displayed. When the user click outside of it, then the content loses its focus and it gets hidden.
So far, it works great. However, I am encountering two problems.
The first one is that when an element inside the dropdown is clicked (eg: anchor tags), the dropdown loses focus, which it shouldn't.
The second one is that when the dropdown toggle is clicked while the dropdown content is being displayed, the dropdown should close instead of closing then re-opening due to the click registered on the dropdown toggle.
HTML:
<div class="dropdown">
Dropdown toggle
<div class="dropdown-content" tabindex="0">
<ul>
<li>
My profile
</li>
<li>
Log out
</li>
</ul>
</div>
</div>
CSS:
.dropdown {
position: relative;
}
.dropdown.is-open .dropdown-content {
display: block;
}
.dropdown-content {
display: none;
position: absolute;
top: 100%;
width: 100%;
padding: 0.5rem 0;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
JS:
class Dropdown {
constructor(element) {
this.element = element;
this.toggle = this.element.querySelector('.dropdown-toggle');
this.content = this.element.querySelector('.dropdown-content');
this.bindings();
}
bindings() {
this.toggle.addEventListener('click', this.open.bind(this));
this.content.addEventListener('keydown', this.handleKeyDown.bind(this));
this.content.addEventListener('focusout', this.close.bind(this));
}
open(e) {
e.preventDefault();
this.element.classList.add('is-open');
this.content.focus();
}
close(e) {
this.element.classList.remove('is-open');
}
handleKeyDown(e) {
if (e.keyCode === 27) {
this.close(e);
}
}
}
document.querySelectorAll('.dropdown').forEach(dropdown => new Dropdown(dropdown));
I have been trying to get my head around on how I would solve these issues without any luck. Any idea on how to solve these issues?

After some testing I found a solution that works. Try the code below
class Dropdown {
constructor(element) {
this.element = element;
this.toggle = this.element.querySelector('.dropdown-toggle');
this.content = this.element.querySelector('.dropdown-content');
this.bindings();
}
bindings() {
this.toggle.addEventListener('click', this.open.bind(this));
this.content.addEventListener('keydown', this.handleKeyDown.bind(this));
this.element.addEventListener('focusout', this.onFocusOut.bind(this),true);
}
onFocusOut(e) {
if (!this.element.contains(e.relatedTarget)) {
this.close(e)
}
}
open(e) {
e.preventDefault();
this.element.classList.toggle('is-open');
this.content.focus();
}
close(e) {
e.preventDefault();
this.element.classList.remove('is-open');
}
handleKeyDown(e) {
if (e.keyCode === 27) {
this.close(e);
}
}
}

Related

Japascript Close modal when user click outside the modal

I have this simple code
const readmore = document.getElementById("read");
const modaloverlay = document.getElementById("modaloverlay");
const closeButton = document.querySelector(".closebutton");
readmore.addEventListener("click", function () {
modaloverlay.classList.add("overlayshows");
});
closeButton.addEventListener("click", function () {
modaloverlay.classList.remove("overlayshows");
});
window.addEventListener('click', function(e){
if ((modaloverlay.classList.contains("overlayshows")) && (e.target != modaloverlay)) {
modaloverlay.classList.remove("overlayshows");
}
});
.overlay {
background: rgba(0,0,0,.9);
padding: 20px;
position: fixed;
top: 10px;
bottom: 10px;
left: 0;
right: 0;
align-items: center;
justify-content: center;
display: none;
max-width: 600px;
margin: 0 auto;
color: #fff
}
.overlayshows {
display: block;
}
.closebutton {
cursor: pointer;
float: right;
}
<div class="modal">
<h1>Content</h1>
<button id="read">READ MORE</button>
</div>
<div class="overlay" id="modaloverlay">
<span class="closebutton">X</span>
<div class="modalinfo" >
Morecontent
</div>
</div>
When i click the button the modal is opened, this part is easy; i know that if i remove the last part of js it will work, but i want that if you click out the modal, the modal is closed, i dont know what is wrong.
Thanks :)
This solution creates a modal singleton to make it easier to manage the lifecycle of the component. It also uses event delegation for easy event management. The key problem with your solution was not preventing the modal click event from propagating.
const modal = {
CLASSES: {
SHOW: 'overlayshows',
CLOSE_BUTTON: 'closebutton',
MODAL: 'modaloverlay',
READ: 'read'
},
isVisible: false,
el: document.getElementById("modaloverlay"),
initialize() {
modal.addEvents();
},
show() {
modal.el.classList.add(modal.CLASSES.SHOW);
modal.isVisible = true;
},
hide() {
modal.el.classList.remove(modal.CLASSES.SHOW);
modal.isVisible = false;
},
addEvents() {
modal.removeEvents();
modal.el.addEventListener('click', modal.eventHandlers.onModalClick);
window.addEventListener('click', modal.eventHandlers.onWindowClick);
},
removeEvents() {
modal.el.removeEventListener('click', modal.eventHandlers.onModalClick);
window.removeEventListener('click', modal.eventHandlers.onWindowClick);
},
eventHandlers: {
onModalClick(event) {
event.stopImmediatePropagation();
if (!event.target) {
return;
}
if (event.target.classList.contains(modal.CLASSES.CLOSE_BUTTON)) {
modal.hide();
}
},
onWindowClick(event) {
if (event.target.classList.contains(modal.CLASSES.READ)) {
modal.show();
} else {
modal.hide();
}
}
}
}
modal.initialize();
W3schools has a good tutorial on modals: https://www.w3schools.com/howto/howto_css_modals.asp
The code is as follows for closing a modal if a user clicks outside of it:
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}

clicking for show div but hide again + make body position stay

i make profile form, i clicked this, form is show but hidden instally
I want to click the link if the form appears without disappearing again, and if clicked outside in the form, from hidden and the web position stay without scrolling to up
i code used
$('.profile-link').click(function(e) {
$(".profile-frm").addClass("show-prfrm");
});
$(document).mouseup(function(e) {
var container = $(".profile-frm");
var clickfuncion = $('.profile-link').click;
if (container.is(':visible')) {
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0) {
e.preventDefault();
$('body').width($('body').width());
container.removeClass("show-prfrm");
}
}
});
I think the only tricky part is to put a click handler on the document and do different things when the target element is the button, the menu, or anything else.
const button = document.querySelector('button');
const menu = document.querySelector('#menu');
document.addEventListener('click', event => {
menu.classList.add('hide');
if (event.target == button || event.target == menu)
menu.classList.remove('hide');
});
#menu {
position: absolute;
top: 50;
border: 1px solid #555;
background-color: #555;
border-radius: 10px;
height: 175px;
width: 100px;
}
.hide {
display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<button>Menu</button>
<div id="menu" class="hide"></div>

onmouseover not working in option [duplicate]

I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})​
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})​
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>

webcomponents - hide dropdown menu on window.onclick

dropdown menu is created in shadowDOM
almost perfect,
but the problem is how to hide the dropdown menu when click on any where else in window
class NavComponent extends HTMLElement {
constructor() {
super();
let template = document.currentScript.ownerDocument.querySelector('template');
let clone = document.importNode(template.content, true);
let root = this.attachShadow({ mode: 'open' });
root.appendChild(clone);
}
connectedCallback() {
let ddc = this.shadowRoot.querySelectorAll('.dropdowncontainer')
let dd = this.shadowRoot.querySelectorAll('.dropdown');
let ddc_length = ddc.length
for (let index = 0; index < ddc_length; index++) {
ddc[index].addEventListener('click', e => {
dd[index].classList.toggle('show');
});
}
/** have to update the code ............ */
window.onclick = function (event) {
} /** END - have to update the code ............ */
}
}
customElements.define('app-nav', NavComponent)
please refer this demo for complete code
The best solution, as #guitarino suggested is to define a dropdown menu custom element.
When the menu is clicked, call a (first) event handler that will show/hide the menu, and also add/remove a (second) dropdown event handler on window.
At its turn, the (second) dropdown event handler will call the first event handler only if the action is outside the custom element itself.
connectedCallback()
{
//mousedown anywhere
this.mouse_down = ev => !this.contains( ev.target ) && toggle_menu()
//toggle menu and window listener
var toggle_menu = () =>
{
if ( this.classList.toggle( 'show' ) )
window.addEventListener( 'mousedown', this.mouse_down )
else
window.removeEventListener( 'mousedown', this.mouse_down )
}
//click on menu
this.addEventListener( 'click', toggle_menu )
}
It works with or without Shadow DOM:
customElements.define( 'drop-menu', class extends HTMLElement
{
constructor ()
{
super()
this.attachShadow( { mode: 'open'} )
.innerHTML = '<slot></slot>'
}
connectedCallback()
{
//mousedown anywhere
this.mouse_down = ev => !this.contains( ev.target ) && toggle_menu()
//toggle menu and window listener
var toggle_menu = () =>
{
if ( this.classList.toggle( 'show' ) )
window.addEventListener( 'mousedown', this.mouse_down )
else
window.removeEventListener( 'mousedown', this.mouse_down )
}
//click on menu
this.addEventListener( 'click', toggle_menu )
}
disconnectedCallback ()
{
this.removeEventListener( 'mousedown', this.mouse_down )
}
} )
drop-menu {
position: relative ;
cursor: pointer ;
display: inline-block ;
}
drop-menu > output {
border: 1px solid #ccc ;
padding: 2px 5px ;
}
drop-menu > ul {
box-sizing: content-box ;
position: absolute ;
top: 2px ; left: 5px ;
width: 200px;
list-style: none ;
border: 1px solid #ccc ;
padding: 0 ;
opacity: 0 ;
transition: all 0.2s ease-in-out ;
background: white ;
visibility: hidden ;
z-index: 2 ;
}
drop-menu.show > ul {
opacity: 1 ;
visibility: visible ;
}
drop-menu > ul > li {
overflow: hidden ;
transition: font 0.2s ease-in-out ;
padding: 2px 5px ;
background-color: #e7e7e7;
}
drop-menu:hover {
cursor: pointer;
background-color: #f2f2f2;
}
drop-menu ul li:hover {
background-color: #e0e0e0;
}
drop-menu ul li span {
float: right;
color: #f9f9f9;
background-color: #f03861;
padding: 2px 5px;
border-radius: 3px;
text-align: center;
font-size: .8rem;
}
drop-menu ul li:hover span {
background-color: #ee204e;
}
<drop-menu><output>Services</output>
<ul>
<li>Graphic desing</li>
<li>web design</li>
<li>app design</li>
<li>theme</li>
</ul>
</drop-menu>
<drop-menu><output>tutorial</output>
<ul>
<li>css <span>12 available</span></li>
<li>php <span>10 available</span></li>
<li>javascript <span>40 available</span></li>
<li>html <span>20 available</span></li>
</ul>
</drop-menu>
An unrelated suggestion: you should probably separate .dropdown into its own <app-nav-dropdown> component and assign the 'click' event listeners in its 'constructor' or 'connectedCallback'.
The best idea for your problem is to
ddc[index].addEventListener('click', e => {
if(dd[index].classList.contains('show')) {
dd[index].classList.remove('show');
window.removeEventListener('click', handleDropdownUnfocus, true);
}
else {
dd[index].classList.add('show');
window.addEventListener('click', handleDropdownUnfocus, true);
}
});
Note: I use addEventListener with true, such that the event happens at capture, so that it's will not happen immediately after the .dropdown click handler.
And your handleDropdownUnfocus will look like
function handleDropdownUnfocus(e) {
Array.from(document.querySelectorAll('app-nav')).forEach(function(appNav) {
Array.from(appNav.shadowRoot.querySelectorAll('.dropdown')).forEach(function(dd) {
dd.classList.remove('show');
});
});
window.removeEventListener('click', handleDropdownUnfocus, true);
}
There's a problem with this solution though, that if you click on the menu item again after opening it, it will call both .dropdown and window handlers, and the net result will be that the dropdown will remain open. To fix that, you would normally add a check in handleDropdownUnfocus:
if(e.target.closest('.dropdown')) return;
However, it will not work. Even when you click on .dropdown, your e.target will be app-nav element, due to Shadow DOM. Which makes it more difficult to do the toggling. I don't know how you'd address this issue, maybe you can come up with something fancy, or stop using Shadow DOM.
Also, your code has some red flags... For example, you use let keyword in your for-loop, which is fine. The support for let is very limited still, so you're more likely going to transpile. The transpiler will just change every let to var. However, if you use var in your loop, assigning the handlers in a loop like that will not work anymore, because index for every handler will refer to the last dropdown (because index will now be global within the function's context and not local for every loop instance).

Dropdown menu open on hover instead of click on shopify

I'm trying to edit a shopify theme and the last part I'm stuck on is getting these navigation menus to open on hovering instead of clicking. The css I have for the menus is:
.site-nav {
position: relative;
padding: 0;
text-align: center;
margin: 25px 0;
a {
padding: 3px 10px;
}
li {
display: inline-block;
}
}
.site-nav--centered {
padding-bottom: $gutter-site-mobile;
}
/*================ Site Nav Links ================*/
.site-nav__link {
display: block;
white-space: nowrap;
.site-nav--centered & {
padding-top: 0;
}
.icon-chevron-down {
width: 8px;
height: 8px;
margin-left: 2px;
.site-nav--active-dropdown & {
transform: rotateZ(-180deg);
}
}
&.site-nav--active-dropdown {
border: 1px solid $color-border;
border-bottom: 1px solid transparent;
z-index: 2;
}
}
/*================ Dropdowns ================*/
.site-nav--has-dropdown {
position: relative;
}
.site-nav--has-centered-dropdown {
position: static;
}
.site-nav__dropdown {
display: none;
position: absolute;
left: 0;
padding: $dropdown-padding;
margin: 0;
z-index: $z-index-dropdown;
text-align: left;
border: 1px solid $color-border;
background: $color-bg;
left: -1px;
top: 41px;
.site-nav__link {
padding: 4px 30px 4px 0;
}
.site-nav--active-dropdown & {
display: block;
}
li {
display: block;
}
}
// Centered dropdown
.site-nav__dropdown--centered {
width: 100%;
border: 0;
background: none;
padding: 0;
text-align: center;
}
The HTML and Liquid for the header is:
{% if section.settings.align_logo == 'left' %}
<nav class="grid__item medium-up--one-half small--hide" id="AccessibleNav" role="navigation">
{% include 'site-nav' %}
</nav>
{% endif %}
And the relevant menu Javascript:
/* ================ MODULES ================ */
window.theme = window.theme || {};
theme.Header = (function() {
var selectors = {
body: 'body',
navigation: '#AccessibleNav',
siteNavHasDropdown: '.site-nav--has-dropdown',
siteNavChildLinks: '.site-nav__child-link',
siteNavActiveDropdown: '.site-nav--active-dropdown',
siteNavLinkMain: '.site-nav__link--main',
siteNavChildLink: '.site-nav__link--last'
};
var config = {
activeClass: 'site-nav--active-dropdown',
childLinkClass: 'site-nav__child-link'
};
var cache = {};
function init() {
cacheSelectors();
cache.$parents.on('click.siteNav', function(evt) {
var $el = $(this);
if (!$el.hasClass(config.activeClass)) {
// force stop the click from happening
evt.preventDefault();
evt.stopImmediatePropagation();
}
showDropdown($el);
});
// check when we're leaving a dropdown and close the active dropdown
$(selectors.siteNavChildLink).on('focusout.siteNav', function() {
setTimeout(function() {
if ($(document.activeElement).hasClass(config.childLinkClass) || !cache.$activeDropdown.length) {
return;
}
hideDropdown(cache.$activeDropdown);
});
});
// close dropdowns when on top level nav
cache.$topLevel.on('focus.siteNav', function() {
if (cache.$activeDropdown.length) {
hideDropdown(cache.$activeDropdown);
}
});
cache.$subMenuLinks.on('click.siteNav', function(evt) {
// Prevent click on body from firing instead of link
evt.stopImmediatePropagation();
});
}
function cacheSelectors() {
cache = {
$nav: $(selectors.navigation),
$topLevel: $(selectors.siteNavLinkMain),
$parents: $(selectors.navigation).find(selectors.siteNavHasDropdown),
$subMenuLinks: $(selectors.siteNavChildLinks),
$activeDropdown: $(selectors.siteNavActiveDropdown)
};
}
function showDropdown($el) {
$el.addClass(config.activeClass);
// close open dropdowns
if (cache.$activeDropdown.length) {
hideDropdown(cache.$activeDropdown);
}
cache.$activeDropdown = $el;
// set expanded on open dropdown
$el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'true');
setTimeout(function() {
$(window).on('keyup.siteNav', function(evt) {
if (evt.keyCode === 27) {
hideDropdown($el);
}
});
$(selectors.body).on('click.siteNav', function() {
hideDropdown($el);
});
}, 250);
}
function hideDropdown($el) {
// remove aria on open dropdown
$el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'false');
$el.removeClass(config.activeClass);
// reset active dropdown
cache.$activeDropdown = $(selectors.siteNavActiveDropdown);
$(selectors.body).off('click.siteNav');
$(window).off('keyup.siteNav');
}
function unload() {
$(window).off('.siteNav');
cache.$parents.off('.siteNav');
cache.$subMenuLinks.off('.siteNav');
cache.$topLevel.off('.siteNav');
$(selectors.siteNavChildLink).off('.siteNav');
$(selectors.body).off('.siteNav');
}
return {
init: init,
unload: unload
};
})();
Any help would be greatly appreciated. I feel so silly asking a simple question like this. I just can't figure out where to put :hover in the code. It seems pretty strait forward but I can't get it. You can see the site here: AlexandIvy.myShopify.com and the password to view it is staysk. I'm just talking about the top navigation menus.
This is the code from the console:
<nav class="grid__item medium-up--one-half small--hide" id="AccessibleNav" role="navigation">
<ul class="site-nav list--inline " id="SiteNav">
<li class="site-nav--has-dropdown">
<a href="/collections/bedding" class="site-nav__link site-nav__link--main" aria-has-popup="true" aria-expanded="false" aria-controls="SiteNavLabel-bedding">
Bedding
<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon--wide icon-chevron-down" viewBox="0 0 498.98 284.49"><defs><style>.cls-1{fill:#231f20}</style></defs><path class="cls-1" d="M80.93 271.76A35 35 0 0 1 140.68 247l189.74 189.75L520.16 247a35 35 0 1 1 49.5 49.5L355.17 511a35 35 0 0 1-49.5 0L91.18 296.5a34.89 34.89 0 0 1-10.25-24.74z" transform="translate(-80.93 -236.76)"></path></svg>
<span class="visually-hidden">expand</span>
</a>
<div class="site-nav__dropdown" id="SiteNavLabel-bedding">
<ul>
<li>
Sheet Sets
</li>
</ul>
</div>
</li>
Since you're using JS to hide/show the dropdowns, I suggest you do this if you're comfortable with JQuery.
$('.site-nav--has-dropdown').hover(function() {
if ($(this).hasClass('activated')){
$(this).removeClass('activated');
$(this).children('.site-nav__dropdown').css('display', 'none');
}
else{
$(this).addClass('activated');
$(this).children('.site-nav__dropdown').css('display', 'block');
}
});
The idea behind this is that the child closest to .site-nav--has-dropdown which has a class name .site-nav__dropdown can be activated on hover. You can use pol's code too which provides a different (and shorter) approach.
You should use mouseover/mouseout methods in jquery.
$('.site-nav--has-dropdown').mouseover(function() {
$(this).children('.site-nav__dropdown').show();
});
$('.site-nav--has-dropdown').mouseout(function() {
$(this).children('.site-nav__dropdown').hide();
});
Or just use css :hover,
to better support touch devices you should add :focus too.
.site-nav--has-dropdown:hover .site-nav__dropdown,
.site-nav--has-dropdown:focus .site-nav__dropdown {
display: block;
}
jsfiddle demo: sfiddle.net/8p33qh9h

Categories

Resources