Skip to content

Instantly share code, notes, and snippets.

@jpetto
Created November 5, 2012 19:51
Show Gist options
  • Save jpetto/4019937 to your computer and use it in GitHub Desktop.
Save jpetto/4019937 to your computer and use it in GitHub Desktop.
jQuery Event Delegation
<!DOCTYPE html>
<html>
<head>
<title>Nav Delegation</title>
<style type="text/css">
#member-error {
background: #c44a17;
padding: 10px;
color: #fff;
font-weight: 800;
}
.hidden { display: none; }
.members-only {
color: #c44a17;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="member-error" class="hidden">
You must be a member!
</div>
<nav id="nav-main">
<ul>
<li><a href="http://google.com">Projects</a></li>
<li><a href="http://google.com" class="members-only">Forums</a></li>
<li><a href="http://google.com">Search</a></li>
<li><a href="http://google.com" class="members-only">Rewards</a></li>
</ul>
</nav>
<article>
<header>
<h1>Cupcake Ipsum</h1>
</header>
<p>Candy chocolate bar muffin lollipop jelly marshmallow lemon drops chocolate. I love pudding marshmallow applicake donut toffee apple pie donut.</p>
<p>Candy canes danish sesame snaps liquorice I love. Tart sugar plum liquorice marzipan gingerbread croissant dessert. Ice cream I love pie lollipop topping I love.</p>
</article>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// event delegation
// apply a handler to the #nav-main element that will only fire when an <a> is clicked
$('#nav-main').on('click', 'a', function(e) {
// we get the specific <a> tag from e.target
// wrapping e.target in $ gives us a jQuery object
var a = $(e.target);
// we can call jQuery functions on the object now to see if it's a members only link
if (a.hasClass('members-only')) {
e.preventDefault();
$('#member-error').removeClass('hidden');
setTimeout(function() {
$('#member-error').addClass('hidden');
}, 1000);
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment