0

I've got this code and it works perfectly, but what I want is to add the classes to an array and loop through them and get the value, and whenever a class (that is inside the array I looped) is clicked I'll add the click event it will call a function to do something (scroll to the clicked class).

My old code without the array:

$(
    'header .navbar-nav > li > a,'
    +'.services .arrow > .arrowDown,'
    +'.alert a,'
    +'.incorrect-page .message p a'
).click(function () {              
    var data_value = $(this).data('value');

    // check if data_value exist in the current page
    if ($('#' + data_value).length) {
        if (data_value === 'home') {
            // if it's home, load homepage
            document.location.href = "/kazamizaNEW/";
            // alert("/kazamizaNEW/index?page=1")
        } else {
            // smooth scroll to that element
            $('html').animate({
                scrollTop: $('#' + data_value).offset().top
            }, 500);
        }
    }  else {
        // else do this:
        document.location.href = "/kazamizaNEW/#" + data_value;
    }
});

What I tried to do and failed:

var smoothScrollElements = {
    'headerNav': 'header .navbar-nav > li > a,',
    'serScroll': '.services .arrow > .arrowDown,',
    'alertLink': '.alert a,',
    'incorLink': '.incorrect-page .message p a'
};

var keys = $.map(smoothScrollElements, function (scrollLink, key) {
    // Loop for each Element in the array
    $(scrollLink).each(function (element, index) {
        element.click(function() {
            console.log("the class you clicked: " + element + "!");
        });
    });
});

I hope that I explained what I want. Thanks a lot.

1 Answer 1

1

smoothScrollElements is invalid. Remove commas at the end of the string. And each() is unnecessary in your $.map() function.

var keys = $.map(smoothScrollElements, function (scrollLink, key) {
    $(scrollLink).click(function() {
        console.log("the class you clicked: " + scrollLink + "!");
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.