HIDE & SHOW ELEMENTS WITH JQUERY & MEDIA QUERIES

date:17th May, 16 | by: Joe Karanka | views:
blog website ideas

Responsive design often has its ups and downs, especially during production.


On one particular project that I happened to have been working on, I was required to display a certain element at a particular position on page load and after adjustments of the viewport to certain dimensions, the element was supposed to be displayed at another position. Media Queries would have easily done the job, though they are limited to some certain extent. Luckily, there is jQuery- a JavaScript library that is easy to implement, and most importantly, works magic!

The approach is to first get the current computed width of matched elements or set the width of every matched element.

 

  $(window).width(); // Returns width of the browser viewport
  $(document).width(); // Returns width of HTML document

 

...and with retrospect to my design:

 

 $(document).ready(function(){ 
   if($(window).width() > 768) {
     $(".bookingTab").css("display","none");
    }
  });

 

...and using the IF - ELSE statement, you can set the value at which the element will be visible.

 

  $(window).ready(function(){
   if($(window).width() > 768) {
    $(".bookingTab").css("display","none");
    }else{
      $(".bookintTab").css("display","block"); 
    }
   });

 

Finally, using media query at the respective value, use DISPLAY: NONE; to hide the element.

Creativity is allowing yourself to make mistakes. Design is knowing which ones to keep.

tags