Skip to content

Instantly share code, notes, and snippets.

@kimili
Last active January 12, 2021 16:46
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 kimili/f1dbfaf83532298c6fd80931c9d4678e to your computer and use it in GitHub Desktop.
Save kimili/f1dbfaf83532298c6fd80931c9d4678e to your computer and use it in GitHub Desktop.
Card helper utility. Takes a DOM element with a link in it and makes the entire thing clickable, based on the first link within.
const CardHelper = {
init(selector = '.card') {
this.card = null;
this.link = null;
this.mousedowntime = 0;
this.selector = selector;
const body = document.querySelector('body');
body.addEventListener('mousedown', this.handleCardMouseDown.bind(this));
body.addEventListener('mouseup', this.handleCardMouseUp.bind(this));
},
handleCardMouseDown(evt) {
const target = evt.target;
this.card = target.closest(this.selector);
// Not a card? Bail out.
if (!this.card) {
return;
}
// Exclude direct clicks on links or buttons
if (
target.closest('a') ||
target.closest('input') ||
target.closest('button')
) {
return;
}
this.link = this.card.querySelector('a');
if (!this.link) {
return;
}
this.mousedowntime = new Date().getTime();
},
handleCardMouseUp() {
if (!this.link) {
return;
}
const mouseuptime = new Date().getTime();
if (mouseuptime - this.mousedowntime < 200) {
this.link.click();
}
}
};
export default CardHelper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment