How to direct a link to one of the tabs of a Bootstrap 4 list group

Asked

Viewed 35 times

0

need to access a tab of a bootstrap 4 list group from a link on another page.

On the first page I have: link1 Link2 link3

When I click on Link2, I want you to go to the other page and already fall right into the tab of the matching list group (Link2). But by default it always comes with the first sample link (using the 'show class'').

On the flaps are: link1 Link2 link3

I thought of the following alternative:

When I click on the link1 I direct to the page but in the url I already put the id of the list tab getting like this:

...with/page.html#Link2

And then I apply the following function:

<script>
var url = location.href;  // pega o url da página
var string = url.split('#'); // aqui faz a quebra da linha na #
var valor = string[1]; // aqui atribui o valor a variavel 
</script>

My variable value is set to Link2'

My idea was to make a simple condition:

If value = 'id-do-Link2' click on the link with the tab id I want.

So, by clicking on the first page, the Nav runs the function, checks which id is the url and already loads the correct tab.

Get it? It must have been confusing! Can you help me with this simple function? If variable contains string click on tab element.

1 answer

0


You can trigger a click on the tab link automatically:

var url = location.href;
var string = url.split('#');
var valor = string[1];
$("a[href='#"+valor+"']").click(); // dispara o click

Note that the click will be in the tab that has the href equal to the hash in the URL.

To change the URL in the browser according to the tab clicked, you can use the function history.replaceState():

$("#myTab a").on("click", function(){
   history.replaceState(null, null, $(this).attr("href"));
});

Don’t forget to change the id #myTab by the id of your list where flaps.

  • 1

    That’s good, Sam, only the first line of code you’ve added has solved the problem! Thank you!

Browser other questions tagged

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