Michael Schwartz
Michael Schwartz

Reputation: 8415

JQuery Resize Browser Width, Hide Div at > 1024

What I'm trying to accomplish is simple. Say you're viewing a website, and you go to view it on an iPod Touch, a small tablet or maybe you resized the browser yourself, but the width of the browser is either at 1024px or lower, and the text inside the div fills over all the extra content. So the answer for me is simple for the basic construction. Hide the text when the browser comes to 1024px or lower.

I tried this, but it doesn't seem to be working. Any help here?

$(window).resize(function(){
    if($(window).width() < 1024 ) {
        $('h2#head1').hide();}
    else {
        $('h2#head1').show();};
});

Upvotes: 1

Views: 2767

Answers (1)

moribvndvs
moribvndvs

Reputation: 42497

In this case, it's because your selector is off (should be 'h2 #head1' or simply '#head1', not h2#head1). See http://jsfiddle.net/ERBKU/

However, I have a couple other observations:

  1. This won't process until the window is actually resized, meaning on load it won't have been processed. So you'd need to double down on this logic on load. However, that leads me to point 2...
  2. I think you'll get better results by combining a little jQuery and CSS. I am referencing a methodology used in Modernizr and early jQuery Mobile. Basically, on load and resize, you want to detect the viewport width, and if it meets a width threshold, you tack a specific CSS selector to the html element. This selector can influence the CSS properties of the target element if it meets the threshold. See this fiddle: http://jsfiddle.net/b5LYq/1/ The benefit to this route is you only need one little snippet of jQuery, and you can easily tweak the display properties of additional elements by just adding more layout rules in CSS. Much easier than maintaining a big block of jQuery to manipulate the page to get it to display the way you want. Furthermore, you can add additional layout thresholds and it will still work the same.

Upvotes: 2

Related Questions