Can I attach a javascript file to HTML hyperlink?


#1

Hi!
So, I’m relatively new to using javascript but I kind of don’t have the time to learn it methodiously because i have to submit a school project by the end of the week.
My question is can I attach a JavaScript alert to a HTML hyperlink, so that when the link is clicked an alert pops up, and if I can how do I do it?
I’d appreciate any type of assistance.
Thanks!


#2

why a hyperlink? Its more tricky, given the hyperlink will attempt to redirect you.

There is onclick attribute:

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/onclick

which you can use to execute JS code, including calling a Javascript function

furthermore, you will need preventDefault() if you want to prevent the hyperlink from redirecting.

even listeners written in JS (so not the onclick attribute) would be neater, but this is is easier


#3

Well, the whole point of it is to have hyperlink that leads back to the main page and a js that alerts about whatever (I haven’t come up with that part yet). That’s starting to look close to impossible now.


#4

isn’t easier to include JS in your main page and give an alert when the page load? Maybe you need to look into location then:

https://developer.mozilla.org/en-US/docs/Web/API/Window/location