Media query and Jquery for detecting screensize

I have an HTML table where I want to adjust the width of table headers (<th>) based on the browser size. In other words, I aim to create a responsive table using media queries or jQuery to detect screen size and apply corresponding styles."

<table class="table table-bordered table-striped mt-3" style="table-layout: fixed;">
 <thead>
  <tr>
   <th style="width: 10%;">ID</th>
   <th style="width: 5%;"></th>
   <th style="width: 5%;"></th>
   <th style="width: 30%;">Remark</th>
   <th style="width: 20%;">Date and Time</th>
  </tr>
 </thead>
</table>


Media query detecting size of desktop, tablet and mobile

/* Default styles */
table {
 table-layout: fixed; /* Ensures equal column widths */
}

/* Tablet-sized screens (adjust breakpoint as needed) */
@media (min-width: 768px) and (max-width: 1023px) {
 table th {
  /* Adjust widths for tablet */
  width: 20%; /* Example, adjust as needed */
 }
}

/* Mobile-sized screens */
@media (max-width: 767px) {
 table th {
  /* Adjust widths for mobile */
  width: 25%; /* Example, adjust as needed */
 }
}


jquery detecting size of desktop, tablet and mobile

$(document).ready(function() {
 function checkWidth() {
  var winWidth = $(window).width();

  if (winWidth >= 768 && winWidth <= 1023) {
   // Code for screen width between 768px and 1023px
   console.log("Tablet-sized screen");
  } else if (winWidth <= 767) {
   // Code for screen width less than or equal to 767px
   console.log("Mobile-sized screen");
  } else {
   // Code for screen width greater than 1023px
   console.log("Desktop-sized screen");
  }
 }

 checkWidth(); // Initial check

 $(window).resize(function() {
  checkWidth(); // Recheck on window resize
 });
});


In jquery you can use .addClass and .removeClass

Additional search keyword: responsive webpage, responsive html, media query responsive, jquery responsive, jquery detect screen size, jquery detect width, jquery add remove class

Last update on Jul 15, 2024

Tags: media query, jquery

Back to Posts

Comments

No comments yet.

ForceTeach Corporation 2024