I'm making a web site with only one page, I need put the menu and the header (there are joined) fixed in the top of the navigator, but I need that when the user press click on one menu item the page scroll itself to a specific location. I try with fixed position in css and anchor for the links, but the content go to the top of the navigator window and stay under the menu and the header.
Asked
Active
Viewed 116 times
3 Answers
0
You can use window.scrollTo to scroll to your specific position
$("#item").click(function(){
window.scrollTo(500,0);
});

sn_92
- 488
- 3
- 11
0
With jQuery:
$(".menuitem").click(function(e){
e.preventDefault(); // prevent the default behavior of the anchor
var top = $($(this).attr("data-target")).offset().top; // get the original ("bad") position
var headerHeight = $("#menu").outerHeight(true); // get the height of the menubar
var scrollTop = top-headerHeight; // calculate the wanted scrollTop
$(window).scrollTop(scrollTop); // this is the scroller code
// you can use animate or other fancy effect
// if you need, for example:
// $("html, body").aminate({"scrollTop": scrollTop}, 700);
});
#menu {
background-color: #777777;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100px;
}
.menuitem {
color: #FFFF00;
}
.target {
margin-top: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="menu">
<!-- (I suggest to separate data-target from href) -->
<a href="#target1" class="menuitem" data-target="#target1">MENU 1</a>
<a href="#target2" class="menuitem" data-target="#target2">MENU 2</a>
<a href="#target3" class="menuitem" data-target="#target3">MENU 3</a>
<a href="#target4" class="menuitem" data-target="#target4">MENU 4</a>
<a href="#target5" class="menuitem" data-target="#target5">MENU 5</a>
</div>
<div id="target1" class="target"><a name="target1"></a> <!-- (<a> is for noscript support) -->
TARGET 1
</div>
<div id="target2" class="target"><a name="target2"></a>
TARGET 2
</div>
<div id="target3" class="target"><a name="target3"></a>
TARGET 3
</div>
<div id="target4" class="target"><a name="target4"></a>
TARGET 4
</div>
<div id="target5" class="target"><a name="target5"></a>
TARGET 5
</div>

Dávid Horváth
- 4,050
- 1
- 20
- 34
-
If you want the scroll to animate instead of jump to position --> $("body").animate({scrollTop:scrollTop}, 400) – webkit Oct 13 '14 at 14:05
0
To do this, you can set a callback function for the animate command which will execute after the scroll animation has finished.
For example:
var body = $("html, body");
body.animate({scrollTop:0}, '500', 'swing', function() {
alert("Finished animating");
});
Where that alert code is, you can execute more javascript to add in further animation.

Pedro Loureiro
- 355
- 3
- 16