Show div in desktop and hide in mobile using jquery

Show div in desktop and hide in mobile using jquery.

To show a <div> element on desktop and hide it on mobile using jQuery, you can use the $(window).resize() event handler along with the .hide() and .show() methods. Here's an example:

HTML:

<div id="myDiv">
  This div will be shown on desktop and hidden on mobile.
</div>

JavaScript (jQuery):

$(document).ready(function() {
  // Function to handle the window resize event
  function handleResize() {
    if ($(window).width() < 768) { // Adjust the breakpoint as needed
      $('#myDiv').hide(); // Hide the div on mobile
    } else {
      $('#myDiv').show(); // Show the div on desktop
    }
  }

  // Initial handling of the window resize event
  handleResize();

  // Bind the window resize event to the handling function
  $(window).resize(function() {
    handleResize();
  });
});

In the above code, we first define the handleResize() function to handle the window resize event. Inside this function, we check the width of the window using $(window).width() and compare it to a specified breakpoint (in this case, 768 pixels). If the window width is less than the breakpoint, we use the .hide() method to hide the <div>. Otherwise, we use the .show() method to show the <div>.

Next, we call the handleResize() function initially to handle the window resize event when the page loads. Then, we bind the resize() event to the handleResize() function so that it is called whenever the window is resized.

This way, the <div> will be shown on desktop and hidden on mobile, and the visibility will be automatically updated when the window is resized.

Freelance Website Designer and Developer

Hire Our Website
Designer and Developer

Recent Solutions

Freelance Website Designer and Developer
Indoc Web Design

Copyright © 2024 All rights reserved
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram