最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent page scrolling up on collapsing accordion section. Bootstrap 4 - Stack Overflow

programmeradmin2浏览0评论

Its a bootstrap 4 accordion the body section is bigger than usual that's why when section collapses content below it scrolls up with it.

I'm using this code to scroll to top of clicked header and cancel the scrolling caused by collapsing of previously opened section.

but it seems to run before that collapsing previous one. I researched on internet and unable to find a solution.

code is little lengthy sharing relevant snippet. Also populating card-body using ajax on clicking header.

                <div id="accordion" class="row"></div>
                <script>
                    success: function(res) {
                        let resultHtml = ``;
                        for (let i = 0; i < res.length; i++) {
                            resultHtml +=
                            `
                            <div class="card col-12 px-0">
                                <div class="card-header" id="heading${i}">
                                  <h5 class="mb-0">
                                    <button class="btn btn-link w-100 text-left btn-expand" data-toggle="collapse" data-target="#collapse${i}" data-place-id="${ res[i].place_id }" aria-expanded="false" aria-controls="collapse${i}"><img class="place-icon" src="${ res[i].icon }">
                                      ${ res[i].name }
                                    <span class="float-right">Rating: ${ getStars(res[i].rating) }</span>
                                    </button>
                                  </h5>
                                </div>
                                <div id="collapse${i}" class="collapse" aria-labelledby="heading${i}" data-parent="#accordion">
                                    <div class="card-body"></div>
                                </div>
                            </div>`;
                     }
                     $("#accordion").html(resultHtml);



                     $('#accordion').on('hide.bs.collapse', function () {
                        $('html, body').animate({
                            scrollTop: $( event.target ).parent().offset().top
                        }, 400);                            
                });

              </script>

shown.bs.collapse and hidden.bs.collapse are not working for me. show.bs.collapse and hidde.bs.collapse are firing but still no working.

Thank You

Its a bootstrap 4 accordion the body section is bigger than usual that's why when section collapses content below it scrolls up with it.

I'm using this code to scroll to top of clicked header and cancel the scrolling caused by collapsing of previously opened section.

but it seems to run before that collapsing previous one. I researched on internet and unable to find a solution.

code is little lengthy sharing relevant snippet. Also populating card-body using ajax on clicking header.

                <div id="accordion" class="row"></div>
                <script>
                    success: function(res) {
                        let resultHtml = ``;
                        for (let i = 0; i < res.length; i++) {
                            resultHtml +=
                            `
                            <div class="card col-12 px-0">
                                <div class="card-header" id="heading${i}">
                                  <h5 class="mb-0">
                                    <button class="btn btn-link w-100 text-left btn-expand" data-toggle="collapse" data-target="#collapse${i}" data-place-id="${ res[i].place_id }" aria-expanded="false" aria-controls="collapse${i}"><img class="place-icon" src="${ res[i].icon }">
                                      ${ res[i].name }
                                    <span class="float-right">Rating: ${ getStars(res[i].rating) }</span>
                                    </button>
                                  </h5>
                                </div>
                                <div id="collapse${i}" class="collapse" aria-labelledby="heading${i}" data-parent="#accordion">
                                    <div class="card-body"></div>
                                </div>
                            </div>`;
                     }
                     $("#accordion").html(resultHtml);



                     $('#accordion').on('hide.bs.collapse', function () {
                        $('html, body').animate({
                            scrollTop: $( event.target ).parent().offset().top
                        }, 400);                            
                });

              </script>

shown.bs.collapse and hidden.bs.collapse are not working for me. show.bs.collapse and hidde.bs.collapse are firing but still no working.

Thank You

Share Improve this question edited Nov 29, 2022 at 10:46 dan1st 16.6k17 gold badges102 silver badges133 bronze badges asked Sep 22, 2018 at 5:05 TechNerdXpTechNerdXp 4173 gold badges8 silver badges26 bronze badges 4
  • 1 downvotes are a way of sorting out the useful questions from the not-so-useful ones. Once a question is downvoted, it will appear lower on search results since it is not going to be as useful as other similar answers on different sites may be. – mike510a Commented Sep 22, 2018 at 5:11
  • Also can you provide a fully working code snippet plete with HTML elements etc so we can reproduce the bug you are having? The code you provided is not sufficient... see How to Ask – mike510a Commented Sep 22, 2018 at 5:13
  • Yes I'm editing the question.. – TechNerdXp Commented Sep 22, 2018 at 5:16
  • @mike510a I've edited my question. I'm using accordion with bootstrap cards generated in ajax success . – TechNerdXp Commented Sep 22, 2018 at 5:29
Add a ment  | 

3 Answers 3

Reset to default 3

it only occurs when the content of the card-body is longer then the browser. simultaneously it happens only when you use data-parent.

since the card-header with the open card-body is way up the page the collapse ponent pushes everything below up to its position. In a way it does what it is supposed to do.

so there is a choice to make. either you have to give up closing open cards when another one is opened (not using data-parent) or use the script that scrolls the card-header to the top, which was my choice.

I know this is not the answer you expect but until someone finds a better solution these choices are the best we have.

I modified hidden.bs.collapse and changed it to shown.bs.collapse as well as added the event parameter to your function() immediately following the event

 $('#accordion').on('shown.bs.collapse', function(event) {

seems to have done the trick.

See working example below:

<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <title>Business Info</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="apple-touch-icon" href="">
  <link rel="shortcut icon" href="" type="image/x-icon">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn./bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

  <!-- Font Awesome -->

  <link href="https://maxcdn.bootstrapcdn./font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

  <style>
    .place-icon {
      height: 42px;
    }
    
    .review_user_pic {
      width: 42px;
      vertical-align: middle;
    }
    
    .accordion-loading {
      max-width: 350px;
    }
    
    .loader-contanier {
      align-items: center;
    }
  </style>
</head>

<body>

  <div class="d-flex">
    <div class="w-75 m-auto">
      <div class="row place-search-form form-group mt-3">
        <input class="col-12 col-md-4 form-control" type="text" name="" id="city" value="" placeholder="City" required>
        <input class="col-12 col-md-4 form-control" type="text" name="" id="keyword" value="" placeholder="Keyword" required>
        <input class="col-12 col-md-4 btn btn-primary" id="btn" type="button" value="search" />
      </div>
      <div class="controlls row mb-2">
        <span class="toggle-reviews btn btn-sm btn-light m-auto col border-right">Show Reviews</span>
        <span class="toggle-news btn btn-sm btn-light m-auto col">Show News</span>
      </div>
      <div id="accordion" class="row">
        <div class="card col-12 px-0">
          <div class="card-header" id="heading0">
            <h5 class="mb-0">
              <button class="btn btn-link w-100 text-left btn-expand" data-toggle="collapse" data-target="#collapse0" data-place-id="ChIJz8eQTjsFGTkRbTcXvpkUQC0" aria-expanded="true" aria-controls="collapse0"><img class="place-icon" src="https://maps.gstatic./mapfiles/place_api/icons/restaurant-71.png">
                                Hardee's
                                <span class="float-right">Rating: <i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star-o" aria-hidden="true" style="color: gold;"></i>&nbsp;</span>
                            </button>
            </h5>
          </div>
          <div id="collapse0" class="collapse show" aria-labelledby="heading0" data-parent="#accordion" style="">
            <div class="card-body">
              <h5>Hardee's [Lahore]</h5>
              <p>Address: MM Alam Rd, Block C 2 Gulberg III, LAHORE PAKISTAN, Lahore, Punjab, Pakistan</p><a href="https://www.hardees./">Website: https://www.hardees./</a>
              <p>Alexa Rank: 126275</p>
              <div class="news my-5">
                <h5>News</h5>
                <h6>Hardee's employee robbed while making nightly deposit - The Lebanon Enterprise</h6>
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNG-azwNvbB02Rk6UgV8lNhZHGD4JA&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.lebanonenterprise./content/hardee%25E2%2580%2599s-employee-robbed-while-making-nightly-deposit">The Lebanon Enterprise</a>
                <br>
                <hr>
                
                <br>
                <hr>
                <h6>Carl's Jr., Hardee's add Froot Loops Mini Donuts to menu – and they taste just like the cereal - USA TODAY</h6><img class="news-img" src="//t3.gstatic./images?q=tbn:ANd9GcQbfoZmCYgG4eQd4BVfEE6RLnVedEt6KI-ieZhJX1eB8eluTJzaDQVW7ZDxnTGsQBlc5wJd8lCb">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNFazpe2c-TITQViRcs93OKGo_JpHw&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;cid=52780024485508&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.usatoday./story/money/food/2018/08/29/hardees-carls-jr-froot-loops-mini-donuts/1131551002/">USA TODAY</a>
                <br>
                <hr>
                <h6>Win a TV! Hardee's Super Fan Contest! - WWBT NBC12 News</h6>
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNFBBsJoQp-AT_Om7OmgD65fztbJCg&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.nbc12./sports/super-fan/">WWBT NBC12 News</a>
                <br>
                <hr>
                <h6>Hardee's hepatitis scare sent 2000 for treatment. Now, customers seek damages. - Charlotte Observer</h6><img class="news-img" src="//t3.gstatic./images?q=tbn:ANd9GcTtapRl4pzjE6B5wGywiU4DrNF6cjxRIeXVlYdBbqcneur9rx7ZHqTCLOY8cuUD4-GWeF-qFL4m">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNEHEOa5PnMAB1ZKNQRtmymLU4mFwg&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.charlotteobserver./news/local/article217792415.html">Charlotte Observer</a>
                <br>
                <hr>
                <h6>Man hospitalized, police investigating after stabbing at downtown Billings Hardee's - Billings Gazette</h6><img class="news-img" src="//t1.gstatic./images?q=tbn:ANd9GcTiy_FG-VGEnJE44iK5smUe5eHQOvMOO8fDGV0vqegqlBiXw8_CvVaLnp9huyEwdsoWnJUAIcmj">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNEyIlPxTEIpO7R9rqX3SCMS5S396A&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;cid=52780025325127&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://billingsgazette./news/local/man-hospitalized-police-investigating-after-stabbing-at-downtown-billings-hardee/article_901c7f62-a313-577e-b8fd-05050d92477f.html">Billings Gazette</a>
                <br>
                <hr>
                <h6>Hardees wants class action lawsuit dismissed after hepatitis A outbreak - WSOC Charlotte</h6><img class="news-img" src="//t0.gstatic./images?q=tbn:ANd9GcT6nRPPD65nzoSzjfl-hb2fV55dw5uhMxz6Ziis9mEk0TitS_ikf4BpvloDAtRoQKAh4VLDGJ6-">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNFbkOqbdy3b3jTTqfbnlaUS4VjqZQ&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.wsoctv./news/local/hardees-wants-class-action-lawsuit-dismissed-after-hepatitis-a-outbreak/826949737">WSOC Charlotte</a>
                <br>
                <hr>
                <h6>Carl's Jr., Hardee's add Fruit Loops mini donuts to its menu - ABC Action News</h6><img class="news-img" src="//t3.gstatic./images?q=tbn:ANd9GcQrqT9d1CqaNCeBF2km6yJJ729YjrFSGapEpzLwnc6L24XIS8QCItF8QBdIwSC3vYJgoji7n9yi">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNGB0wE313LrKUl9tIKlYzel2-9Jtw&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;cid=52780026051382&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.abcactionnews./lifestyle/carl-s-jr-hardee-s-add-fruit-loops-mini-donuts-to-its-menu">ABC Action News</a>
                <br>
                <hr>
                <h6>Hardee's launches new Froot Loops donuts - wtkr.</h6><img class="news-img" src="//t2.gstatic./images?q=tbn:ANd9GcR0aaGT_ChbJdl17xUHff9ZCGIOJoo18VenPxv8uBy25tyKEGeoaw9RxbMY4QyGEvsURxsykJjl">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNHaVXPnV5OjAfyn8nRc4avb9A9ShQ&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;cid=52780023879969&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://wtkr./2018/08/28/hardees-launches-new-froot-loops-donuts/">wtkr.</a>
                <br>
                <hr>
                <h6>WANTED: Suspect who allegedly robbed Verizon store wearing Hardee's uniform - KMOV.</h6><img class="news-img" src="//t1.gstatic./images?q=tbn:ANd9GcSdpLX4twIv0VQpXhaNoiszqGYZzExA_4KOmVVn-Xhp3cYxboKKY_z4QOoA8FItq-JGGLtp0W2f">
                <p></p><a href="http://news.google./news/url?sa=t&amp;fd=R&amp;ct2=us&amp;usg=AFQjCNEYimeqG2KUffZqcw1e8mdGX5FXig&amp;clid=c3a7d30bb8a4878e06b80cf16b898331&amp;cid=52780048450108&amp;ei=PACoW-DTLcX_zAbtxr_QCg&amp;url=https://www.kmov./news/wanted-suspect-who-allegedly-robbed-verizon-store-wearing-hardee-s/article_2276a4d0-bac0-11e8-b0e0-efdd94499d26.html">KMOV.</a>
                <br>
                <hr>
              </div>
            </div>
          </div>
        </div>
        <div class="card col-12 px-0">
          <div class="card-header" id="heading1">
            <h5 class="mb-0">
              <button class="btn btn-link w-100 text-left btn-expand collapsed" data-toggle="collapse" data-target="#collapse1" data-place-id="ChIJV_dJILEDGTkRy_qFDSboqXE" aria-expanded="false" aria-controls="collapse1"><img class="place-icon" src="https://maps.gstatic./mapfiles/place_api/icons/restaurant-71.png">
                                Builder's fast food
                                <span class="float-right">Rating: <i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;</span>
                            </button>
            </h5>
          </div>
          <div id="collapse1" class="collapse" aria-labelledby="heading1" data-parent="#accordion" style="">
            <div class="card-body">
              <h5>Builder's fast food [Lahore]</h5>
              <p>Address: Hadayatullah Block Hidayatullah Block Mustafa Town, Lahore, Punjab, Pakistan</p>
              <p>Phone: 0321 4880266</p>
              <div class="reviews">
                <h5>Reviews</h5>
                <h6><img class="review_user_pic" src="https://lh5.googleusercontent./-uq1iF8RXHWY/AAAAAAAAAAI/AAAAAAAAABM/8nmKcVJW6NM/s128-c0x00000000-cc-rp-mo/photo.jpg"> Farooq Ahmad</h6>
                <p><i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star"
                    aria-hidden="true" style="color: gold;"></i>&nbsp;<i class="fa fa-star" aria-hidden="true" style="color: gold;"></i>&nbsp;</p>
                <p>Tower Burger is 
发布评论

评论列表(0)

  1. 暂无评论