theliadir
theliadir

Reputation: 37

Bootstrap 4: Create a direct link to an ID inside a collapsed accordion's card which then opens the card and jumps to the ID

I would like to create a link to an ID which is inside a collapsed card (Bootstrap 4). When I click the link - the card should be opened and jump to the ID.

I tried with: www.link.com#linktoidinsidecollapsedcard but that does not open the collapsed card.

Any ideas?

UPDATED CLARIFICATION

Although I'd like do the same scroll tho the element ID #ourElement from another page, using link like <a href="//thisismysite.com/subpage/item.php#ourElement">Link on the block 3 inside ID</a>

Upvotes: 2

Views: 1673

Answers (2)

DanielBlazquez
DanielBlazquez

Reputation: 1055

Try this at the end of the document:

if(location.hash != null && location.hash != ""){$(location.hash + '.collapse').collapse('show');}

Reference: https://stackoverflow.com/a/60937622/321480

Upvotes: 0

focus.style
focus.style

Reputation: 6760

For this task we need a small script on jQuery. Your link should have class .accordionLink and # in href and looking like this <a href="#ourElement" class="accordionLink">...</a>. The text on the right of # is the ID of our desired element.

I put <div id="ourElement"><b>Our element</b></div> inside according #3. Try to click the link Link on the block 3 inside ID. I but one ling on the beginning and another one inside Block #1. Both works. You can use as match links with class .accordionLink as you want and anywhere you want.

There are comments in script, so you will understand.

// better to use some class like '.accordionLink' and check a link for it so other links with '#' will work as they should, without a conflict
$('a[href*="#"].accordionLink').click(function (e) {		
  e.preventDefault();
  let desiredId = $.attr(this, 'href').split('#')[1]; //getting data from the left and right from #, and calling the right one by '[1]'  
  // checking if element with this ID exists
  if ($('#'+desiredId).length ) {
    // showing the closes parent '.collapse' of our ID
    $('#'+desiredId).closest('.collapse').collapse('show'); 
    setTimeout(function () {
      // smooth animation to our ID
      $('html, body').animate({
        scrollTop: $('#'+desiredId).offset().top
      }, 500);
    }, 300); // this interval is necessary for bootstrap to complete the accordion animation
  }		
});
/* not necessary */
body {
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>

<a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h2>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        <a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a><br> 
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.        
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        <div id="ourElement"><b>Our element</b></div>
        rd dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

UPDATED

Added the part if (location.hash), in which we are looking for hash in an URL. Now, if you'll open the page using address //thisismysite.com/subpage/item.php#ourElement - this code will look for #ourElement and if it is somewhere inside the .collapse. Using <a href="//thisismysite.com/samepage#ourElement"> on the same page as /samepage is totally OK, it will only trigger a script without page reloading. And you don't need class="accordionLink" for a link from another page.

// looking for hash in URL
if (location.hash) {
  let desiredHash = window.location.hash.split('#')[1]; //getting data from the left and right from #, and calling the right one by '[1]'  
  desiredFunction(desiredHash); // calling function and sending hash
}

// better to use some class like '.accordionLink' and check a link for it so other links with '#' will work as they should, without a conflict
$('a[href*="#"].accordionLink').click(function (e) {		
  e.preventDefault();
  let linkId = $.attr(this, 'href').split('#')[1]; //getting data from the left and right from #, and calling the right one by '[1]'  
  desiredFunction(linkId); // calling function and sending hash
});

function desiredFunction(desiredId) {
  // checking if element with this ID exists and if the element inside of accordion
  //if (($('#'+desiredId).length) && ($('#'+desiredId).closest('.collapse').length)) {
  if (($('#'+desiredId).length) && ($('#'+desiredId).closest('.collapse').length)) {
    // showing the closes parent '.collapse' of our ID
    $('#'+desiredId).closest('.collapse').collapse('show'); 
    setTimeout(function () {
      // smooth animation to our ID
      $('html, body').animate({
        scrollTop: $('#'+desiredId).offset().top
      }, 500);
    }, 300); // this interval is necessary for bootstrap to complete the accordion animation
  }	
}
/* not necessary */
body {
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>

<a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
              Collapsible Group Item #1
            </button>
      </h2>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        <a href="#ourElement" class="accordionLink">Link on the block 3 inside ID</a><br> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.
        Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente
        ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
              Collapsible Group Item #2
            </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
              Collapsible Group Item #3
            </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
        <div id="ourElement"><b>Our element</b></div>
        rd dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt
        sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

Upvotes: 1

Related Questions