Last active
January 12, 2021 16:46
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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