A better way to implement custom jQuery code?

I’m having an issue with my jquery code, not being always triggered.
What I’m trying to do is to toggle a class when the user scrolls more than 70px. It works fine but not always.

For example, sometimes after editing a topic or creating/editing a category and then clicking the logo to go back to the homepage, the code won’t work unless I’ll refresh the page.

I could also use the native docker class, but in my example is added only after scrolling the entire hero section’s height, and I want the class to be added sooner.

So is there a better way of including custom jquery codes in a discourse theme?

The code I’m using:

$(function() {
    //caches a jQuery object containing the header element
    var header = $("body.categories-list .d-header-wrap, body.navigation-topics .d-header-wrap");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll >= 70) {
            header.addClass("cd-active");
        } else {
            header.removeClass("cd-active");
        }
    });
});

Testing theme:

https://theme-creator.discourse.org/?preview_theme_id=4529

Discourse is an SPA, a single-page application. This also means the javascripts you add in <head> only execute once on the initial page load unless you use the correct methods. You may need to change your code to fire based upon an event handler / listener.

HTH

2 Likes

Yes, I think I should but meanwhile, I’ve found the fix. The problem was that I was using body.categories-list instead of body.navigation-categories. The body.categories-list is also used on subcategory pages and while I was on those pages the code wasn’t working at all ( I have no idea why ).

Edit: Still the same issue, not always working.

I’ve changed my code and it seems it works now but it will fire on every page. In my previous code, I was trying to isolate the code only on the .navigation-categories and .navigation-topics pages but probably this is the problem. Anyway, all help is appreciated. Thanks.

$(function() {
   $(window).on("scroll touchmove", function () {
    if ($(this).scrollTop() > 70) {
      $('.d-header-wrap').addClass('cd-active');  
    } else {
      $('.d-header-wrap').removeClass('cd-active');  
    }   
  });	  
});