I wrote this if
statement event listener to add and remove a class to a couple links based on changed.owl.carousel
. However, I know this is not the most DRY method in writing the code and often find myself writing more than is needed. Is there a cleaner way to write this code?
owl.on('changed.owl.carousel', function(event) {
if ($('.owl-item.active>.item.slide3').length>0) {
$('#link3').addClass('hover');
} else if (jQuery('.owl-item.active>.item.slide4').length>0) {
$('.link').removeClass('hover');
$('#link4').addClass('hover');
} else {
$('.link').removeClass('hover');
}
})
1 Answer 1
if ($('.owl-item.active>.item.slide3').length>0) {
$('#link3').addClass('hover');
} else if (jQuery('.owl-item.active>.item.slide4').length>0) {
$('.link').removeClass('hover');
$('#link4').addClass('hover');
} else {
$('.link').removeClass('hover');
}
I notice the use of both $
and jQuery
. Suggesting you use one or the other, but not both. While both are perfectly valid, it's best to keep it consistent.
Also, put a space on both sides of the >
for readability. It's not immediately clear that there's actually 2 classes in the selector.
Comparing against 0
is redundant as the number can already double as a boolean. length
is a number that's either 0
or a positive integer. Any non-zero number is truthy while 0
is falsy.
I would suggest you avoid IDs. IDs should be unique but nothing prevents you or other code from reusing the same ID. This will lead to problems. For instance, $('#selector')
will only return the first of many elements with the same ID.
Without the accompanying HTML, we cannot make assumptions as to how the compare logic works. This is as far as the review goes.
somename*
(where * is a number) naming patterns show up in code. This code smell oftentimes indicates that you have places where you can improve your approach. It is hard to say here though without context. \$\endgroup\$link
as both a class name andlink#
as an ID. IMO that makes it harder to read, and easier to make a mistake using one when you need the other. \$\endgroup\$