Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAngelic Sanoy
Full Stack JavaScript Techdegree Student 6,583 PointsWhat's the difference between event handler and html event?
I just noticed that sometimes an event is wrap into html like which I assume this is called html event.
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
While others are wrap in Javascript like below:
btn.addEventListener('click', () => {
const rndCol = rgb(${random(255)}, ${random(255)}, ${random(255)})
;
document.body.style.backgroundColor = rndCol;
});
Wondering when I should use the event handler and html event. Also, does the event handler always accompanied with event listener?
1 Answer
Steven Parker
231,210 PointsIn both cases, an event listener is being established along with a handler function to run when the event occurs. The listener is implied when setting the handler using the HTML properties.
However, it is considered "best practice" to establish listeners using JavaScript code., and that method also provides additional functionality. Setting handlers with HTML properties is typically used only for testing or in trivial programs which otherwise have no JavaScript component.
Angelic Sanoy
Full Stack JavaScript Techdegree Student 6,583 PointsAngelic Sanoy
Full Stack JavaScript Techdegree Student 6,583 PointsThank you Steve, your answer is on point. So in short, if we compare this into HTML/CSS. HTML event is like an inline style while event handler is the css.
Steven Parker
231,210 PointsSteven Parker
231,210 PointsClose, setting a handler by assigning an "on___" HTML property could be considered an "inline" method, but there really isn't any CSS component to a handler. It's all JavaScript.