\n\n\nThe onclick here becomes the trigger for doSomethingCool and event.preventDefault() acts as the anchoring Gordon Freeman, keeping your page position stable!","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Nikita Barsukov","url":"https://explain.codes//author/nikita-barsukov"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2025-01-11T19:15:01.524Z","dateModified":"2025-01-11T19:15:03.269Z"}
Explain Codes LogoExplain Codes Logo

How to use a link to call JavaScript?

javascript
event-listeners
dom-manipulation
unobtrusive-javascript
Nikita BarsukovbyNikita Barsukov·Jan 11, 2025
TLDR

Invoking JavaScript with a hyperlink can be achieved via the <a> tag with an href="#" attribute to abstain from the default navigation, and an onclick attribute to fire up your function. Within your function, do not forget to invoke event.preventDefault() to stay at the same position on the page (or keep it from navigating away).

<a href="#" onclick="doSomethingCool(event);">Click me!</a> <script> function doSomethingCool(event) { event.preventDefault(); // Stops the refresh... and also the rain if I could alert('JavaScript called. It says hi!'); } </script>

The onclick here becomes the trigger for doSomethingCool and event.preventDefault() acts as the anchoring Gordon Freeman, keeping your page position stable!

A leap to button interactivity

For those actions not requiring navigation, transposing it to buttons from hyperlinks can boost accessibility and adhere to semantic goodness of HTML. After all, you would not use a spoon to cut a steak, right?

<button onclick="onlyCoolButtonsAllowed();">Action</button> <script> function onlyCoolButtonsAllowed() { // Your JavaScript code here } </script>

Use buttons for actions like a superhero, and leave navigation to links, they are good at that!

Smooth operator: unobtrusive JavaScript

Unobtrusive JavaScript pledges allegiance to cleanliness. It keeps your markup fresh and the functionality in separate quarters. Instead of raising the onclick flag, yoke the event within your JavaScript code:

window.onload = function() { document.getElementById('myLinkId').addEventListener('click', function(event) { event.preventDefault(); // This function won't... runaway, it won't... runaway }); };

Event listeners are our welcoming committee after the DOM fully loads earth's browser inhabitants. Nothing starts without a window.onload.

Dancing with the dynamic elements

For dynamic elements, event delegation runs the show. It helps you to pin just a single event listener to a parent element. Just like that, it fires for all the little descendants matching the selective criteria:

document.body.addEventListener('click', function(event) { if (event.target.matches('.dynamicEtchASketch')) { event.preventDefault(); // Fun fact: JavaScript was originally called Mocha. More coffee? } });

With event delegation, it's not all about power but efficiency complemented with a simplified handling for multiple items.

Secure JavaScript: keeping the Honor Guard on

Triggering JavaScript from a link must invite Content Security Policy (CSP) to the party. It lays down the security red carpet and restricts inline event handlers for security reasons. Much like a designated driver, secure alternatives ask for event handlers in external JavaScript files.

Separation of codes: The Switzerland policy

Following Switzerland's doctrine, we aim for peaceful code co-existence. This boosts your readability and scales your code mountain. JavaScript behavior, like a well-behaved guest, should never be inline within HTML tags:

// I predict, this inside your JS, predicts a prediction probably. document.addEventListener('DOMContentLoaded', (event) => { document.getElementById('linkId').addEventListener('click', (e) => { e.preventDefault(); // No. I am your father... err function. }); });

Swedish House Mafia retired, but we don't need to fill that void with jQuery if pure JavaScript will do. For added firepower, jQuery provides the .on() method to attach event handlers for that full-throttle gig.

DOM manipulation: JavaScript's puppeteer moment

Calling upon JavaScript from a hyperlink, the DOM manipulation takes the stage. Changing content, styles, or even the attitude of page elements, it's the key playmaker in interactive web theatrics:

function newNarrative() { document.getElementById('story').innerHTML = 'Once upon a time... again.'; }

Errors and grace: The Beauty and the Beast

Turning on the unobtrusive JavaScript mode, even during errors or disabled JavaScript scenarios, your website's usability remains like a beautiful beast. Both error handling and graceful degradation share an intense romance to give the user experience a happy ending.

if (window.addEventListener) { window.addEventListener('error', function(e) { // Error handling or art of logging }); } else { window.attachEvent('onerror', function(e) { // Those old folk browsers need attention too }); }