I have website with a javaScript function that should scroll to section on page when user clicks a navigation item. This script worked before I made changes to my nav menu. I can not figure out how to reference the ID's in the javaScript correctly.
Here is HTML nav menu:
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Data Detective</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a id="home" href="#homeSect">HOME</a></li>
<li><a id="about" href="#aboutSect">ABOUT</a></li>
<li><a id="portfolio" href="#portfolioSect">PORTFOLIO</a></li>
<li><a id="contact" href="#contactSect">CONTACT</a></li>
</ul>
</div>
</div>
</div>
Here is the javaScript:
$(document).ready(function() {
setBindings();
});
//Allow screen to Scroll to selected section
function setBindings() {
$("nav ul li a").click(function (tip) {
tip.preventDefault();
var sectionID = "#" + tip.currentTarget.id + "Sect";
alert('button id ' + sectionID);
$("html body").animate({
scrollTop: $(sectionID).offset().top
}, 1000);
});
}
The document. getElementById() method returns an Element object that represents an HTML element with an id that matches a specified string. If the document has no element with the specified id, the document. getElementById() returns null .
The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id. The syntax for id is: write a hash character (#), followed by an id name. Then, define the CSS properties within curly braces {}.
You should use .navbar
class.
Please change:
$("nav ul li a").click(function (tip) {
TO
$(".navbar ul li a").click(function (tip) {
Further more, I recommend you to use var sectionID = $(this).attr('href');
instead var sectionID = "#" + tip.currentTarget.id + "Sect";
because it's more simply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With