Sherwin Flight
Sherwin Flight

Reputation: 2363

Hide elements that won't fit on screen using jQuery

I'm looking for a way to dynamically hide/show a elements based on if they would fit into the current screen width.

Normally objects are either pushed down onto a new row, or cause horizontal scrolling, if elements will not fit onto the screen. That's not what I'm trying to do.

I was also hoping to do this without media queries, and would rather use jQuery.

I think what I need to do is for each element check if the right edge of the element would be outside of the right edge of the screen, and if so hide that element. However this is a bit above my jQuery experience.

I have the elements all aligned horizontally already, and when the screen gets smaller they push down the page and show in multiple rows. I assume with jQuery I can get a more fluid effect, whereas with CSS media queries I'd need to set up a bunch of queries to show/hide each element based on screen size.

Can someone point me in the right direction? There may already be a similar question here on SO, but I'm not quite sure what to search for, as I haven't had much luck so far finding out how to do this searching SO, or using Google.

I have found solutions like How to hide elements on screen size? but they all seem to require setting some predefined screen sizes. I was hoping to have jQuery do this automatically without specifying widths ahead of time.

Upvotes: 0

Views: 161

Answers (1)

Jaxon
Jaxon

Reputation: 345

Something like this?

It will check every element that you select that it's width is less than the viewport width, if so it hides it.

$(function() {

var checkScreenSize = function (){

    var viewportWidth = $( window ).width();

    $('.select-elements-you-want-to-check').each(function () {
        if($(this).width() > viewportWidth){
            $(this).hide();
        }
        else {
            $(this).show();
        }
    });


}

// run on doc ready
checkScreenSize();

// run on window resize
$( window ).resize(checkScreenSize);

});

Upvotes: 1

Related Questions