Skip to content

Instantly share code, notes, and snippets.

@kapitancho
Created October 17, 2015 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kapitancho/a5710288260d89871b65 to your computer and use it in GitHub Desktop.
Save kapitancho/a5710288260d89871b65 to your computer and use it in GitHub Desktop.
Nodeclick mini function
<!DOCTYPE html>
<html>
<head>
<script>
//Add a single event listener that handles one or more actions based on the data-* attributes.
var nodeclick = function (container, mapping, omitHref) {
container.addEventListener ('click', function(event) {
var el = event.target;
while (el != container) {
if (el.href && omitHref !== false) return;
var ds = el.dataset;
for (var m in mapping) {
if (ds[m]) {
event.preventDefault();
mapping[m] (ds[m], el);
return;
}
}
el = el.parentNode;
}
}, true);
};
document.addEventListener ('DOMContentLoaded', function() {
nodeclick (document.querySelector ('ul'), {
itemId : function(value) {
alert ('Item click: ' + value);
},
itemDelete : function(value, element) {
alert ('Item delete: ' + value + ', element = ' + element);
}
});
}, true);
</script>
</head>
<body>
<ul>
<li data-item-id="123">
Item 123
<span data-item-delete="123">delete</span>
</li>
<li data-item-id="456">
Item 456
<span data-item-delete="456">delete</span>
<a href="#">External link</a>
</li>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment