luka luka - 1 month ago 7
jQuery Question

Shorten jQuery Multiple If Statements

I have three jQuery functions that include an if/else if statement. Basically each different function toggles/removes a different css class depending on if the window width is less than or greater than than a certain value.

All the functions are very similar and I have been trying to shorten them/combine them into one function. I'm pretty sure it can be shortened quite easily, but I can't figure out how!

Here is the jQuery:

jQuery(document).ready(function($) {
$('.exampleimg').click(function() {
$('.about').hide(600);
if (($(window).width() > 670) && ($(this).hasClass('exampleimgopen'))) {
$(this).removeClass('exampleimgopen');
}
else if ($(window).width() > 670) {
$('.exampleimg').removeClass('exampleimgopen');
$(this).addClass('exampleimgopen');
}
});
});

jQuery(document).ready(function($) {
$('.exampleimg').click(function() {
$('.about').hide(600);
if (($(window).width() < 670) && ($(this).hasClass('exampleimgopen2'))) {
$(this).removeClass('exampleimgopen2');
}
else if ($(window).width() < 670) {
$('.exampleimg').removeClass('exampleimgopen2');
$(this).addClass('exampleimgopen2');
}
});
});

jQuery(document).ready(function($) {
$('.exampleimg').click(function() {
$('.about').hide(600);
if (($(window).width() < 540) && ($(this).hasClass('exampleimgopen3'))) {
$(this).removeClass('exampleimgopen3');
}
else if ($(window).width() < 540) {
$('.exampleimg').removeClass('exampleimgopen3');
$(this).addClass('exampleimgopen3');
}
});
});

Answer

To retain all the functionality I had to create a function that took 3 variables:

function image(condition, windowWidth, css) {
    return function() {
    $('.about').hide(600);
    var windowCondition = condition($(window).width(), windowWidth);
        if (windowCondition && ($(this).hasClass(css))) {
        $(this).removeClass(css);
        } 
        else if (windowCondition) {
        $('.exampleimg').removeClass(css);
        $(this).addClass(css);
        }
    }
}   

var lessThan = function(a, b) { return a < b; };
var greaterThan = function(a, b) { return a > b; };

var func1 = image(greaterThan, 669, 'exampleimgopen');
var func2 = image(lessThan, 670, 'exampleimgopen2');
var func3 = image(lessThan, 540, 'exampleimgopen3');

$('.exampleimg').click(func1);
$('.exampleimg' ).click(func2);
$('.exampleimg').click(func3);

And also create two variables to manage the less than and greater than 670px

The just call the functions for every class on click