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

JavaScript

Adding JavaScript to a link ( click activate ) !

How to run a JS code when the user clicks on a link ??

3 Answers

Steven Parker
Steven Parker
243,318 Points

You 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.

I 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
Steven Parker
243,318 Points

I don't remember exactly which course or stage but it shouldn't take you long to get where this is presented.

Thanks