The problem
The code you're writing using jQuery becomes unmaintainable and hard to read
The solution
Short of stop using jQuery (if that is an option you can use then go for it and use Vue.js instead) start by extracting reusable components/plugins from your code. Writing such a plugin is nothing hard - just a frame where you put your code in:
(function($) {
$.fn.myPlugin = function(options) {
const defaults = {
// TODO: add default values for options here
}
const settings = $.extend(defaults, options)
// Either process each element in a loop
return this.each(function() {
// TODO: add the body of what the plugin should do
// 'this
' is the current element when iterating
})
// or operate on all elements at once using other functions
// return this.css({ ... })
}
})(jQuery)
More on authoring jQuery plugins here.
With that in place you're ready to create whatever is used in multiple places like the grownups do and enjoy the pleasure of using method chaining even more!
$('.my-component').myPlugin({ color: red });
Going Webpack!
It is said that once you go Webpack you never go back. If that's your case then you might want to create your plugins as separate modules and let Webpack put it all together nice and easy. To do that you define your plugin as a module that imports jQuery and exports nothing, then you import that module in your main application file.
import $ from 'jquery'
$.fn.myPlugin = function(options) {
const defaults = {
// TODO: add default values for options here
}
const settings = $.extend(defaults, options)
// Either process each element in a loop
return this.each(function() {
// TODO: add the body of what the plugin should do
// 'this
' is the current element when iterating
})
// or operate on all elements at once using other functions
// return this.css({ ... })
}
In main.js
import $ from 'jquery'
import './my-plugin'
$(document).ready(function() {
// use your plugin here
$('.my-component').myPlugin({ color: red });
})
The easiest Webpack configuration that will work in this case is
module.exports = {
entry: __dirname + '/index.js',
output: {
path: __dirname + '/dist',
filename: 'index.js'
},
devtool: 'source-map'
}
In this case you can include the dist/index.js
and you'll have all you need in one place. And that's it! Easy as a lion :)
And last but not least: don't name your plugin myPlugin
. It's lame to do in anything else than a tutorial. Be explicit, use good names, be a good programmer!
Happy coding!
PS
Please be mindful that the function assigned to $.fn.myPlugin
as well as the one that iterates over elements that have been passed on can't be arrow functions because jQuery sets the this
element. Just remember that.