As I put in my comment, it is common that when using links as buttons (something common in material design or bootstrap) the element has the form:
<a href="#" class="btn btn-warning" id="alerta" >Alerta!</a>
And a handler of the type
jQuery(document).on('click', '#alerta', function () {
var msg = 'Usted pinchó alerta';
console.log(msg);
});
When clicking on a link disguised as a button, you are also calling the link #
that is interpreted as a relative route to the current one, i.e. is added to the url.
This serves for example to navigate to an anchor or to the ID of an element contained in the document (so you can make a link to a specific section of a long page).
When you use some kind of router ( Backbone.Router , Vue Router ) that hash in the URL is not harmless. The route is associated with actions within a Single Page App (SPA). For example:
-
link shows the page in the first tab
-
link shows the page in the second tab
Clicking on a link pointing to #
will take you to
http://dominio/#
That does not comply with any pattern expected by the router.
If you do not want the click to change the URL hash, instead of giving them attribute href="#"
give them attribute href="javascript:void(0)"
<a href="javascript:void(0)" class="btn btn-warning" id="alerta" >Alerta!</a>
What exactly happens when using javascript:void(0)
?
Starting the url with javascript:
is a valid prefix for a URI Scheme , such as starting the url with http://
, https://
or magnet:
. Instead of being interpreted as a navigation link, it is interpreted as the execution of a script. In this case, the execution of void(0)
.
The void operator always returns undefined
, so that the browser evaluates the link to undefined
and stays where same.