Why are "anchors" added to the end of the URL?

0

I have a web page that works with tabs and sub-tabs. When in a sun screen I add information when refreshing I do a .click() on the same tab (JavaScript) and a # is added to the end of the URL. The problem is that sometimes names of the tabs of the url are added and the js of the tabs start to fail.

Is there a reason why this is added to the URL, and is there any way to remove them? Thanks

    
asked by Laura Leon 30.08.2018 в 00:31
source

2 answers

0

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.

    
answered by 30.08.2018 / 12:24
source
1

That notation is generally used to redirect to an element with a specific id, for example:

<div id="contenido">
    Contenido
</div>

You can have a link that takes you there:

<a href="#contenido">Ir al contenido</a>

Or you can even go to another page:

<a href="mipagina.html#contenido">Ir al contenido</a>

In your case it seems that it is set to select the tab on which it has been clicked.

Greetings

    
answered by 30.08.2018 в 00:38