How is it correct to write this nested jQuery command?

74 Views Asked by At

I need something like:

function Splitter() {
    if ($(window).width() < 350) OR ($('#right-area').width() < 600) {
        $('.grid-item').css("width", "100%")
    }
    if ($(window).width() < 800) OR ($('#right-area').width() < 800) {
        $('.grid-item').css("width", "50%")
    }
    else {
        $('.grid-item').css("width", "33.3333%")
    }
}

How is it correct to write that? If I replace the OR with ||, it does not work too.

3

There are 3 best solutions below

3
NguyenDY On

You should try it:

function Splitter() {
    if (($(window).width() < 350) || ($('#right-area').width() < 600)) {
        $('.grid-item').css("width", "100%")
    }
    if (($(window).width() < 800) || ($('#right-area').width() < 800)) {
        $('.grid-item').css("width", "50%")
    } else {
        $('.grid-item').css("width", "33.3333%")
    }
}

I thought you forgot "(" or ")" in statement

8
Santi On

When using an if, all corresponding conditions must be wrapped in a single set of parentheses.

Consider the following:

if (a) || (b)   // invalid
if (a || b)     // valid
if ((a) || (b)) // valid

Additionally, I believe your logic is a bit off.

Let's say $(window).width() is 200.

Your first condition is true, so $(".grid-item") gets set to width: 100%.

The second if is also true, so $(".grid-item") gets set to width: 50%.

There is no scenario where $('.grid-item').css("width", "100%") fires and isn't immediately overwritten by $('.grid-item').css("width", "50%").


I believe this may be more along the lines of what you're looking for:

function Splitter() {
    if ($(window).width() < 350 || $('#right-area').width() < 600) {
        $('.grid-item').css("width", "100%")
    }
    else if ($(window).width() < 800 || $('#right-area').width() < 800) {
        $('.grid-item').css("width", "50%")
    }
    else {
        $('.grid-item').css("width", "33.3333%")
    }
}
0
dganenco On

I would advise you, to use another approach. You can try to use jQuery#css with function callback:

var banner = $("#banner-message")
banner.css('width', () => {
 const windowWidth = $(window).width();
 const rightAreaWidth = $('#right-area').width();
 return windowWidth < 350 || rightAreaWidth < 600 ? '100%' : windowWidth < 800 || rightAreaWidth < 800 ? '50%' : '33%';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
</div>