Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access these id's with javaScript

Tags:

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);
    });
}
like image 488
WCoaster Avatar asked Dec 20 '16 08:12

WCoaster


People also ask

How can I get the ID of an element using JavaScript?

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 .

How does ID work in JavaScript?

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 {}.


1 Answers

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.

like image 186
Mihai Alexandru-Ionut Avatar answered Sep 23 '22 17:09

Mihai Alexandru-Ionut