Search code examples
javascriptgulpbrowserify

How to import jQuery then use it in other module imported after it?


So I'm not sure if what I'm asking is possible that way.

I have a Gulp task which us gulp-bro to import module and mix them.

function restaurantScripts() {
    return gulp.src(paths.restaurant.scripts.src)
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(bro({
            transform: [
              babelify.configure({ presets: ['es2015'] }),
              [ 'uglifyify', { global: true } ]
            ]
        }))
        .pipe(rename({
            basename: 'restaurant',
            suffix: '.min'
        }))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(paths.restaurant.scripts.dest));
}

The pointed src look like this :

import './modules/bootstrap.js'
import './modules/navbar.js'
...

In the bootstrap.js I import jQuery and my other vendor.

window.$ = window.jQuery = require('jquery')
window.toastr = require('toastr')
...

Until there it's okay AND I can use jQuery on my website

But this is where it does not work anymore. When I call my personnal module like navbar.js which looks like this :

var navbar = document.getElementsByClassName('nav-bot')[0];
var sticky = navbar.offsetTop;

function navbarSticky() {
    if (window.pageYOffset >= sticky) {
        navbar.classList.add("sticky")
    } else {
        navbar.classList.remove("sticky");
    }
}

window.onscroll = function() {
    navbarSticky()
};

It does not work anymore telling me :

TypeError: navbar is undefined

So obviously I'm missing something there. I think maybe I don't have the right to load my own modules like this. But if not what is the good way to do so pls?


Solution

  • Your error says "navbar is undefined", is it possible that the element you're trying to fetch with getElementsByClassName doesn't exist at the time of this code being executed? Try running this "document.getElementsByClassName('nav-bot')[0];" in the console first.