Writing my jquery code more efficient
Hi there,
I am relatively new to jQuery and javascript coding in general and I am trying to write cleaner and more efficient code. I am actually a designer and not a coder but I try my best. :D
I have some objects on a website that I am animating with AnimateCSS and jquery (
https://github.com/customd/jquery-visible ) and I am wondering if I can write the code more compact to save some kb.
Here is an example:
- var boxes = jQuery('div.box');
var event_list_item = jQuery('#event-list div.card-container');
// check if an element is already visible
boxes.each(function(i, el) {
var el = jQuery(el);
if (el.visible(true)) {
el.addClass('already');
}
});
event_list_item.each(function(i, el) {
var el = jQuery(el);
if (el.visible(true)) {
el.addClass('already');
}
});
...
I have even some more of these elements, so there are a few more blacks of code where I check the visibility and add a class if they are already visible. I would really like to write this more compact or create a function to do that job with each element but I have no idea how.
I am not sure if this is relevant, but the next part actually adds a class and there I have a few of the same blocks as well, so I am also interested to shorten that code, that is related to window.scroll.
var bounceUp = 'bounceInUp';
var zoom = 'zoomIn';
var win = jQuery(window);
// when scrolling happens
win.scroll(function(event) {
boxes.each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
if (!jQuery(this).hasClass("already")) {
el.addClass('animated ' + bounceUp);
}
}
});
event_list_item.each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
if (!jQuery(this).hasClass("already")) {
el.addClass('animated ' + zoom);
}
}
});
...
It would be awesome if somebody could give me an example on how to simply this code and make it more efficient respectively faster to process for the browser.