Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rotaercz's avatar

How would I write this in Vue?

So I wrote the following code using JQuery which is pretty straight forward. It hides the navigation menu when the user scrolls down and will display it when the user scrolls up. I'm still learning Vue and I find it pretty challenging to get out of the JQuery mindset. How can I rewrite this in Vue 2.0?

var scrolled = false;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $("nav").outerHeight();

$(window).scroll(function(event){
    scrolled = true;
});

setInterval(function() {
    if (scrolled) {
        hasScrolled();
        scrolled = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();
    
    if(Math.abs(lastScrollTop - st) <= delta) // make sure user scrolled more than delta
        return;
    
    if (st > lastScrollTop && st > navbarHeight) {
        if( !$("nav").hasClass("mini-menu") ) {
            $("nav").removeClass("nav-show").addClass("nav-hide");
        }
    } 
    else {
        if(st + $(window).height() < $(document).height()) {
            $("nav").removeClass("nav-hide").addClass("nav-show");
        }
    }
    
    lastScrollTop = st;
}
0 likes
5 replies
ejdelmonico's avatar

As @jlrdw mentioned, there is a great deal of information and examples on the vuejs site. Hopefully, you are not trying to use Vue because it's new and cool. If you have it working great in jQuery, then just use jQuery.

rotaercz's avatar

@jirdw Nothing is wrong with the jquery mindset. I'm learning something new.

@ejdelmonico I'm learning new stuff and just want to grasp Vue js better. I've wrote some code to toggle classes and update states based on the data. But I want to go further.

In the above code, how would I go about setting up the setInterval in Vue so it doesn't update for every bit of scrolling without creating a memory leak?

jlrdw's avatar

@rotaercz and technically nothing new, still just javascript. In the core of jquery, or core of Vue probably the exact same lines of code is what make an element appear. Just my thought.

Please or to participate in this conversation.