Skip to content

Instantly share code, notes, and snippets.

@elusiveunit
Created November 22, 2013 21:07
Show Gist options
  • Save elusiveunit/7606886 to your computer and use it in GitHub Desktop.
Save elusiveunit/7606886 to your computer and use it in GitHub Desktop.
As implemented on WebPlatform Docs. Makes use of event capturing through the useCapture parameter for addEventListener, so IE9+ or any modern browser. http://docs.webplatform.org/wiki/Main_Page
<p>Let's have a <a href="#before">link before</a></p>
<div class="dropdown">
<a href="#admin">Admin</a>
<ul>
<li><a href="#admin-one">Pages</a></li>
<li><a href="#admin-two">Posts</a></li>
<li><a href="#admin-three">Users</a></li>
<li><a href="#admin-four">Settings</a></li>
</ul>
</div>
<div class="dropdown">
<span>Users</span>
<ul>
<li><a href="#users-one">View all</a></li>
<li><a href="#users-two">Add new</a></li>
<li><a href="#users-three">Subscriptions</a></li>
</ul>
</div>
<p>Let's have a <a href="#after">link after</a></p>
if ( document.body.addEventListener ) {
var $dropdowns = $('.dropdown'),
i = 0,
len = $dropdowns.length,
dropdown;
for ( i = 0; i < len; i++ ) {
dropdown = $dropdowns[i];
dropdown.addEventListener( 'focus', function () {
$(this).addClass('focus');
}, true );
dropdown.addEventListener( 'blur', function () {
$(this).removeClass('focus');
}, true );
}
}
.dropdown > ul {
/* Style the dropdown and hide it */
}
.dropdown:hover > ul,
.dropdown > a:focus + ul,
.dropdown.focus > ul {
/* Show the dropdown */
}
if ( document.querySelectorAll && document.body.addEventListener ) {
var dropdowns = document.querySelectorAll('.dropdown'),
i = 0,
len = dropdowns.length,
dropdown;
for ( i = 0; i < len; i++ ) {
dropdown = dropdowns[i];
dropdown.addEventListener( 'focus', function () {
this.className += ' focus';
}, true );
dropdown.addEventListener( 'blur', function () {
this.className = this.className.replace( /\s+focus\b/, ' ' );
}, true );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment