Reputation: 27
Here is javascript
code for scrolling down the sections :
<script type="text/javascript">
$(function() {
$('.nav').click(function() {
var id = $(this).attr('id');
$('html, body').animate({
scrollTop: ($('#' + id + '.section').offset().top)
}, 1000);
});
})();
</script>
I have 3 sections in this page and every section has different background color :
<div class="section" id="1" style="background-color:#0F0">
<section>
</section>
</div>
<div class="section" id="2" style="background-color:#0FF">
<section>
</section>
</div>
<div class="section" id="3" style="background-color:#CF6">
<section>
</section>
</div>
It works great, but it has a bug. Sometimes when I scrolling with that javascript
code it shows the section 1 in like 500 milliseconds then go to the other section.
Here is jsfiddle
How can I fix that for not showing section 1 when I don't need it.
It's better on firefox
than chrome
or IE
. I mean sometimes it happen on firefox
but always happen on other browsers.
It's something like bug how can I fix it?
Any help will be appreciated.
Thanks in advance
Upvotes: 0
Views: 157
Reputation: 495
In your HTML links just replace href with the hash tag of the relevant div.
$(function() {
$('.nav').click(function() {
var id = $(this).attr('id');
$('html, body').animate({
scrollTop: ($('#' + id + '.section').offset().top)
}, 1000);
});
})();
nav {
position: fixed;
width: 100%;
background-color: lightgrey;
text-align: center;
margin-bottom: 20px;
font-size:18px;
font-family:"B Koodak";
}
a {
margin: 0 10px 0 10px;
text-decoration: none;
color: black;
}
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
}
.section {
height: 100%;
padding-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<a class="nav" id="1" href="#1">A</a>
<a class="nav" id="2" href="#2">B</a>
<a class="nav" id="3" href="#3">C</a>
</nav>
<div class="section" id="1" style="background-color:#0F0">
<section>
<p>hi</p>
</section>
</div>
<div class="section" id="2" style="background-color:#0FF">
<section>
<p>how are you</p>
</section>
</div>
<div class="section" id="3" style="background-color:#CF6">
<section>
<p>welcome</p>
</section>
</div>
Upvotes: 3