Open Collapse via Bootstrap URL

Asked

Viewed 189 times

1

How can I open a particular Collapse via URL?

For example: by clicking 'Link 1' he goes to the page 'pagina1' and opens/takes user to Collapse 'link1' (href="pagina1.html#link-1"), in this case Collapse has the ID link1

Just to get an idea of the environment, I set up a basic structure in Jsfiddle. https://jsfiddle.net/wkujfg18/16/

  • Your code is working. It just has a few redundancies. You want to open Collapse when it comes from another page or when you click on the link on the same page?

  • I still get it from JS :S.... It would have to be both... When the user comes from another page or when it is on the same page

  • It’s working in parts, because if I have content (another ID) inside Collapse, how do I redirect? In case he would have to open the Collapse and then take to the content

1 answer

1


You can do it this way:

$("a.nav-link").click(function(e,i){
   if(i){
      var hash = i.ancora ? i.hash : i;
   }else{
      var hash = this.href.match(/#.+/)[0];
   }

   $(hash + '.collapse').collapse('show');

   if(i) hash = i.ancora || hash;

   $('html, body').animate({ scrollTop: $(hash).offset().top - 200 }, 500);
});

$(document).ready(function(){
   var hash = location.hash;
   var params = hash;
   if(!$(hash).hasClass('collapse')){
      hash = "#"+$(hash).closest(".collapse").attr("id");
      params = {hash: "#"+$(hash).closest(".collapse").attr("id"), ancora: params};
   }
   if(hash) $("a.nav-link[href$='"+hash+"']").trigger("click", params);
});

If there is the hash in the URL or if you click on the menu, it will trigger the event click where will open the Collapse.

  • And to get the links to open Collapse and go to an ID inside Collapse? How can I do this kind of interaction?

  • OK! , Since it was not in the question, I will see here.

  • That one -200that you use, would you be what? You don’t want the div to touch the top?

  • I gave an update on the answer. Test there.

  • Sorry for the delay... I made some changes to HTML and JS and it worked! I really appreciate the help!

  • No problem. I’m glad it worked out.

  • I voted +1 on the question, now you can vote tb. Abs!

Show 2 more comments

Browser other questions tagged

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