To recreate your jQuery function into a vanilla JavaScript function, you can use the following approach:
document.addEventListener("DOMContentLoaded", function(event) {
var element = document.querySelector('.test');
function resize() {
if (window.innerWidth < 768) {
element.classList.add('mobile');
} else {
element.classList.remove('mobile');
}
}
// For performance reasons, this method should be
// "debounced" so that it doesn't have to execute
// on every resize event, only when you're done resizing.
window.onresize = resize;
});
You can read up on debouncing and it's benefits here, or you can can check out _.debounce() from lodash.
The absolute best way (IMO) to learn the differences between jQuery and Vanilla JavaScript is to:
- Read the jQuery source code to see how they implement their API.
Because jQuery is just a JavaScript library, you can see the vanilla JavaScript that jQuery uses "behind the scenes" to make all the magic happen.
- While you are working on a jQuery project or feature, as an exercise, try to implement the same project/feature without jQuery, you will quickly learn the reasons why jQuery is so useful, but you will learn more about the DOM and vanilla JavaScript in the browser.
Note that because this particular function is only adding and removing a class based on the window's size, you can get the same effect using @media queries in CSS, which could prove more performant than the JavaScript implementation above.
For example, you could achieve the same result without JavaScript like this:
@media screen and (max-width: 768px) {
.test {
background-color: red;
}
}