nived
nived

Reputation: 141

jQuery scrollTop doesn't scroll the first time

I tried using e.preventDefault(); and return false; at the end of the code those didn't help. Here is my code:

$('.game-nav-inner-game1 .nav-item a').click(function (){
    $('html,body').animate({
        scrollTop: $(".scrollHere").offset().top - 100
    }, 400);
});

And this is my html:

<ul class="nav nav-tabs game-nav game-nav-inner game-nav-inner-game1-events" data-game="game1" data-container="events-container">
<li class="nav-item">
    <a class="nav-link" href="#nameofthemap" data-toggle="tab" aria-controls="nameofthemap">
        <img src="{$smarty.const.SITE_ADDR}/resources/img/game1-game/maps/nameofthemap.jpg" class="img-fluid game1-map" />
    </a>
</li>
</ul>
<div class="tab-content w-100">
   <div class="tab-pane fade scrollHere" id="events-container"></div>
</div>

The

I would appreciate if you can help me.

Upvotes: 2

Views: 597

Answers (2)

Ulysse BN
Ulysse BN

Reputation: 11396

You can use Javascript Vanilla Element.scrollIntoView. Your snippet (simplified for focus reasons) would look like:

$('.click-here').click(() => $('.scroll-here')[0].scrollIntoView(true))
body {
  height: 1500px;
}

.scroll-here {
  margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="click-here" href="javascript:void(0)">Click here</a>
<div class="scroll-here">Scroll here</div>

Upvotes: 0

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

From the code you are posting, I added a wrapper div with class game-nav-inner-game1, since you confirm it is supposed to exist.

And some "spacer" divs...

$('.game-nav-inner-game1 .nav-item a').click(function (){
    $('html,body').animate({
        scrollTop: $(".scrollHere").offset().top - 100
    }, 400);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="game-nav-inner-game1">
  <ul class="nav nav-tabs game-nav game-nav-inner game-nav-inner-game1-events" data-game="game1" data-container="events-container">
    <li class="nav-item">
      <a class="nav-link" href="#nameofthemap" data-toggle="tab" aria-controls="nameofthemap">
        <img src="{$smarty.const.SITE_ADDR}/resources/img/game1-game/maps/nameofthemap.jpg" class="img-fluid game1-map" />
      </a>
    </li>
  </ul>
</div>

<div style="height:150em;"></div>

<div class="tab-content w-100">
 <div class="tab-pane fade scrollHere" id="events-container">HERE</div>
</div>

<div style="height:150em;"></div>

Run the snippet... You'll see that it is working, actually. So your problem is with selectors... Or something else like a typo somewhere.

Upvotes: 2

Related Questions