Created
April 30, 2019 15:00
-
-
Save rileypaulsen/11b27105a460c8fffd071f0a5734eaeb to your computer and use it in GitHub Desktop.
Examples of how to add click listeners using various JavaScript paradigms
This file contains hidden or 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
//Given this HTML, here are the ways to add click events | |
<button id="specialButton">Click Here</button> | |
//traditional plain JS way | |
document.getElementById('specialButton').addEventListener('click', function(){ | |
alert('button clicked!'); | |
}); | |
//-------------------------------------- | |
//ES6 arrow function; will NOT work in IE | |
document.getElementById('specialButton').addEventListener('click', ()=>{ | |
alert('button clicked!'); | |
}); | |
//-------------------------------------- | |
//separate function (best for reusing functionality) | |
document.getElementById('specialButton').addEventListener('click', handleClick); | |
document.getElementById('boringButton').addEventListener('click', handleClick); | |
function handleClick(){ | |
alert('button clicked!'); | |
} | |
//sometimes you might see a function defined as below. It's the same thing as above | |
var handleClick = function(){ | |
alert('button clicked!'); | |
} | |
//-------------------------------------- | |
//jQuery; note: any of the three above ways of defining functions are valid here as well | |
$('button').on('click', function(){ | |
alert('button clicked!'); | |
}); | |
//-------------------------------------- | |
//messy HTML way; note the use of single quotes in JS as to not interfere with HTML's double quotes | |
<button id="specialButton" onclick="alert('button clicked!')">Click Here</button> | |
//-------------------------------------- | |
//React way | |
<button id="specialButton" onClick={()=>{alert('button clicked!')}>Click Here</button> | |
//Note that with React, the onClick thing is just being passed a function (the arrow thing) | |
//so you can pass named functions in to run as well; "this" refers to the current component | |
//also note that when passed in the onClick, there are no parenthesis--just specify the function name | |
handleClick(){ | |
alert('button clicked!'); | |
} | |
render(){ | |
return <button id="specialButton" onClick={this.handleClick}>Click Here</button> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment