AlexRS
AlexRS

Reputation: 31

Trouble with Javascript in Wordpress

I'm trying to create an element in a Wordpress site where a piece of content begins partway down the screen, and sticks to the top of the screen when the user scrolls down.

I've tried various things, and none of them have worked. The most recent attempt uses Javascript to give and take away a class to the content I'm trying to move/fix.

The code is

jQuery( document ).ready(function($) {
    alert( "test1!" );

    var wrap = $("#wrap");

    wrap.on("scroll", function(e) {

        if (this.scrollTop > 147) {
            wrap.addClass("fix-search");
            alert("test2");
        } else {
            wrap.removeClass("fix-search");     
        }

    });

});

The file is enqueuing properly since the first test alert ("test1" fires, but "test2" doesn't fire as I scroll down the screen. I've had that same piece of code working in a modified version of the original code on codepen (http://codepen.io/anon/pen/NqKKVN) so I can only assume this is something weird with Wordpress interacting with Javascript.

So yeah, anyone know a way to either do that I'm wanting to do in a way that will work with wordpress, or to get the above piece of code working properly?

EDIT: This has been solved. For the reference of anyone else with the same problem the piece of code that eventually worked was

jQuery( document ).ready(function($) {



    var scrollTop = $(window).scrollTop();

    function scrollUpdate() { 

        var scrollTop = $(window).scrollTop(); 


        var wrap = $("#menu-all-pages");

        if (scrollTop > 147) {
            wrap.addClass("fix-search");
            console.log("Menu at top");
        } else {
            wrap.removeClass("fix-search");
            console.log("Menu at set point");       
        }

        console.log(scrollTop);
    }

    window.onscroll = scrollUpdate;

});

Upvotes: 0

Views: 96

Answers (1)

Lukas Valatka
Lukas Valatka

Reputation: 103

I have implemented a similar solution in my blog a few years ago. I got it working by scripting this way:

  1. Add a variable scrollTop which would contain the value in pixels

scrolled from the window top.

var scrollTop = $(window).scrollTop();

See, I use jquery function scrollTop applied to the selected object "window". It would return the value scrolled from the very top of the browser. It does work on Wordpress, I have tried it on my blog.

  1. Put this code in a function scrollUpdate. We'll call it later to update

the scroll value from top

function scrollUpdate() {
   var scrollTop = $(window).scrollTop();
}

The function should also contain all the logic checking the scrollTop value and thus applying styles and etc.

  1. Let's make this function be called on every scroll.

    window.onscroll = scrollUpdate;

Try it yourself!

P.S. I got a weird feeling, but you should better use hide / show instead of adding a whole css class to the page.

Upvotes: 1

Related Questions