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 trial
Volkan Kantar
Full Stack JavaScript Techdegree Student 2,820 PointsAdding JavaScript to a link ( click activate ) !
How to run a JS code when the user clicks on a link ??
3 Answers
Steven Parker
243,318 PointsYou would create an "event handler".
Clicking on anything creates an event and in JavaScript you can create a bit of code called an "event handler" and tell the system to run it anytime that event happens.
For example, this bit of code will convert every link on the page into a pop-up message:
document.body.addEventListener('click', e => {
if (e.target.tagName == 'A') {
e.preventDefault();
alert("Hey, don't click that!");
}
});
Are you taking one of the JavaScript courses? This is a common application of JavaScript and is covered to some degree in several of the courses.
Volkan Kantar
Full Stack JavaScript Techdegree Student 2,820 PointsI am... but I haven't gotten that far yet in the chapters.. just want to add my dnd dice js code to a link in my portfolio page... so it can present itself on click
Steven Parker
243,318 PointsI don't remember exactly which course or stage but it shouldn't take you long to get where this is presented.
Volkan Kantar
Full Stack JavaScript Techdegree Student 2,820 PointsThanks