Treehouse: Grow your CSS skills. Land your dream job.

Putting the whole script in one function

  • # April 25, 2012 at 12:20 pm

    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 !

    # April 29, 2012 at 11:20 pm

    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

    # April 29, 2012 at 11:49 pm

    thanks a lot ! for the script !

    # April 30, 2012 at 12:32 am

    No problem.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.