FishOnABicycle FishOnABicycle - 3 months ago 14
Javascript Question

Add/remove classes on scroll (Wordpress)

I'm trying to cause a widget to have one class added and one class removed when a user scrolls down the page by 50px and reverse the process when the user scrolls up again.

Website: Link here

Platform: Wordpress

Theme: Customizr-child

My widget that I'm trying to influence has the

header-widget
class applied to it. This forum thread led me to create:

$(function() {
//caches a jQuery object containing the header element
var header = $(".header-widget");
$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 50) {
$(".header-widget").removeClass("header-widget-tallheader");
$(".header-widget").addClass("header-widget-shortheader");

} else {
$(".header-widget").removeClass("header-widget-shortheader");
$(".header-widget").addClass("header-widget-tallheader");
}
});
});


As the use of script tags in Wordpress is prohibited as standard [1], I opted to install the 'Scripts n Styles' plugin, which apparently overrides that restriction. I have then inserted the above code such that it appears in
head
tag.

Unfortunately however, nothing is happening. Is this that the script tags still aren't processing? Is my coding wrong? Or should I be using AJAX [2]? If the latter, I read through the W3Schools AJAX tutorial [3] but wasn't sure how to apply it under this circumstance.

Thanks in advance if anyone is able to help. I've spent hours and hours looking into this but still appear to be a beginner, so if any answers could be as descriptive as possible please, I'd be grateful.

Footnote:

Due to forum reputation restriction, links I was going to include but can't:

[1]
https://www.godaddy.com/garage/webpro/wordpress/3-ways-to-insert-javascript-into-wordpress-pages-or-posts/


[2]
http://stackoverflow.com/questions/28356137/change-css-when-scroll-down-using-php


[3]
http://www.w3schools.com/ajax/default.asp

Answer

Your code is correct, just add $ = jQuery; before that.

CORRECTED CODE

$ = jQuery;
$(function() {
    //caches a jQuery object containing the header element
    var header = $(".header-widget");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 50) {
            $(".header-widget").removeClass("header-widget-tallheader");
            $(".header-widget").addClass("header-widget-shortheader");

        } else {
            $(".header-widget").removeClass("header-widget-shortheader");
            $(".header-widget").addClass("header-widget-tallheader");
        }
    });
});