The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Putting the whole script in one function

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #37781

    hi, i am creating a one page with scroll.js, i have menu to link through the page, and i want to add a class active to the menu where the user is.

    here is a pen,

    i managed to do that, but i am not sure if it is the right way.

    i want to make the JS append the class name “active” when the user clicks on it and when the user clicks on the other menu item, the classname should be removed from the previous item and append it to the newly clicked item.

    i could not figure it out, how to do, so i added a timeout function, but if you look at the code, i made two different functions for two buttons !

    can anyone help me to create only one function, so that i can do the same !

    ***the code works on browsers, not really sure y it isn’t working in codepen !


    First of all, you need to put your li in an ul or ol.
    Second, if you are using jQuery, according to your source you are, this process can be expedited.


    Script: (assuming jQuery is being called before this)

    (function() {
    //handle click event for the li
    $("#list li").on("click", function(e){
    if(!$(this).hasClass("active")) {
    //if an element by default is not given the
    //"active" class you need to check to see
    //if the object is undefined
    if($("#list .active") != "undefined"){
    //remove the class from the current element
    $("#list .active").removeClass("active");
    //add the class to the elment being clicked
    }else {
    //the element is alread "active"
    return false;

    Hope that helps


    No problem.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.