0

I was wondering if someone could help me out. I am currently developing a wordpress theme using foundation framework on a local host and I would like for the top-bar to change styles on scroll using jquery. I have found that a good solution would be to .addClass or .removeClass based on how far from the top the user scrolls. I have added .active to the .top-bar class in my css. For the jquery code i have put my code in a no conflict wrapper, because wordpress requires you to do so. I have attached my code below, but it doesn't seem to be working at all. My jquery does not get any errors when i test it in JSFiddle, but when i test it using my chrome developer tools i get an error in my jquery, please find the error on commented out in the code below:

My Jquery

jQuery(window).on("scroll", function($) {
    if($(window).scrollTop() > 50) {  //Uncaught TypeError: $ is not a function  
        $(".top-bar").addClass("active");
    } else {

       $(".top-bar").removeClass("active");
    }
});

My CSS

 .top-bar.active{
 background: blue;
    -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    -moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);

 }

1 Answer 1

1

You need to fully reference jQuery throughout your code. It should be...

jQuery(window).on("scroll", function() {
    if(jQuery(window).scrollTop() > 50) {
        jQuery(".top-bar").addClass("active");
    } else {
       jQuery(".top-bar").removeClass("active");
    }
});

When in no-conflict mode you need to always reference jQuery in full and not use the $. No conflict mode exists to prevent conflicts when jQuery is used with other libraries. Some other JS libraries use the $ for a short reference just like jQuery does.

If you want to use the $ as a reference to jQuery when in no-conflict (as WordPress requires), you could always do something like this instead.....

(function($) {
    $(window).on("scroll", function() {
        if($(window).scrollTop() > 50) {
            $(".top-bar").addClass("active");
        } else {
           $(".top-bar").removeClass("active");
        }
    });
})(jQuery); // Fully reference jQuery after this point.
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.