Skip to content

Instantly share code, notes, and snippets.

@DuaelFr
Created February 12, 2018 10:55
Show Gist options
  • Save DuaelFr/e28da6ef60966793ce2b0fc139593001 to your computer and use it in GitHub Desktop.
Save DuaelFr/e28da6ef60966793ce2b0fc139593001 to your computer and use it in GitHub Desktop.
Make a node fully clickable while respecting clicks on links/buttons/contextuals
(function ($, Drupal) {
'use strict';
/**
* Handle click on a node so it redirects to the location of its first link.
*/
Drupal.behaviors.clickableNode = {
attach: function (context, settings) {
$('.js-clickable-node').once('clickableNode')
.on('mouseup.clickableNode', function (evt) {
var $target = $(evt.currentTarget);
var $clicked = $(evt.currentTarget);
// Ensure we didn't click on a link or a button.
if ($clicked.is('a, button') || $clicked.parents('a, button').length) {
return;
}
// Avoid other handlers or default behavior to be triggered, then
// redirect the user.
evt.stopImmediatePropagation();
evt.preventDefault();
var $link = $target.find('a').filter(function () {
return $(this).parents('.contextual').length === 0;
});
if (evt.shiftKey || evt.ctrlKey || evt.button === 1) {
window.open($link.attr('href'), '_blank');
}
else {
location.href = $link.attr('href');
}
})
// Add a visual effect when focusing links inside the content.
.find('a')
.on('focus', function (evt) {
$(evt.target).parents('.js-clickable-node').addClass('is-active');
})
.on('blur', function (evt) {
$(evt.target).parents('.js-clickable-node').removeClass('is-active');
});
}
};
})(jQuery, Drupal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment