11 of 17 menu

Link Navigation Error in JavaScript

Let's analyze an error related to unexpected link navigation. For example, let's take the following link:

<a href="">link</a>

Let's get our link into a variable:

let link = document.querySelector('a');

Let's attach a click handler to our link:

link.addEventListener('click', function() { console.log(this.textContent); });

And here we are in for a surprise. The code is written correctly, however, the output does not appear in the console. The point is that a click triggers navigation via the link. Since nothing is specified in the href attribute, the link simply leads to the current page.

This means that clicking the link leads to the page reloading. That is, our data is output to the console, then the page reloads, and the console becomes empty.

If you look closely, you can see how at the moment of clicking the data appears in the console for an instant, and then disappears. This is the characteristic sign of this error.

Let's look at how we can solve this problem.

First Solution

You should put a hash in the link's href. This will cause the link to point to a specific location on the current page, and clicking the link will not cause a reload. Let's do this:

<a href="#">link</a>

Second Solution

A more advanced way is to cancel the default action using the preventDefault method:

link.addEventListener('click', function(event) { console.log(this.textContent); event.preventDefault(); });
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline