Tag <a href> without changing the location bar

Asked

Viewed 8,700 times

0

I use bootstrap to create applications for the web and I realized that in numerous examples, they use for buttons the <a href> as in this link. I wanted to know how I can work in the same way without having to change the location of my page. Today whenever I need to use this tag, I have to make a reference to a null element on the screen as in the example below:

<a href="#">teste</a>
  • you can use <button class="btn btn-lg btn-Primary" type="button">Primary</button>

  • alias n understood, what would be location bar ? buttons in bootstrap support multiple tags, just you use type='button method'

  • Are you talking about this? http://i.stack.Imgur.com/wMje2.png

  • Try to clarify what you want.

3 answers

2

You probably want to use a link to change a certain part of the page or some action without adding the www.site.com/index.html# right? You can do this in several ways, one of them, although it’s not a very "cool" way using the method preventDefault() of Jquery.

HTML code:

<a href="#" id="meu-link">Meu link</a>
<div id="minha-div">Meu conteúdo.</div>

Jquery code:

$('#meu-link').click(function(e) {
    e.preventDefault(); // Evita o evento padrão da ação seja executado, neste caso, evita que o link chame uma nova URL no browser

    // Ações
    // exemplo: $('#minha-div').html('Meu novo conteúdo.');
});

Documentation: http://api.jquery.com/event.preventdefault/

  • +1. jQuery is always a pleasant and elegant solution :)

1

There is a way to leave a link using javascript.

Example:

<a href="javascript:void(0);">Seu Link</a>

That way your page won’t "skip" when you click on it.

1

There are two possibilities for the tag a do not change the current url.

<a href="#" onclick="return false;">...</a>
<a href="javascript:void(0);">...</a>

One easier solution to implement that I like to use in my scripts is the following (example using jquery):

$(document).ready(function() {
    $("a[href='#']").attr("href", "javascript:void(0);");
});

This way, you don’t need to change the links manually and all the links on the page that have the attribute href equal to # will be automatically changed to not influence the url. But remember that links added on the screen after running the script will not be affected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.