Search code examples
javascripthtmljquerycssmobile

How can I move a section of a webpage for mobile?


I have a section of a website that I would like to display in one spot on the page in the desktop version, and a different spot on the mobile version of the site. After assigning the aforementioned section with the class mobile-remove, I was able to successfully remove the section with the following bit of :

if (window.mobileCheck()) { //verified operational function that checks if the device is mobile
    jQuery(document).ready(function( $ ){
        $('div.mobile-remove').remove();
    });
}

That piece of code works. However, the following attempts to then replace it in the section I named mobile-add failed. I'm sure they're ludicrously incorrect, but I want to demonstrate that I tried this myself first.

$('div.mobile-remove').detach()).appendTo('div.mobile-add'); //The "if" statement being still intact for the following examples

and

var $menu = $('div.mobile-remove').clone();
$('div.mobile-add').append($menu);
$('div.mobile-remove').remove();

Solution

  • If you want it to be appended in one spot for mobile screens, and another spot for desktop on page load, you could check window.innerWidth and then decide from there where you want it to go. `

    $(document).ready(() => {
    
      if (window.innerWidth < 768) {
        $('.class-of-element').append('.mobile-section');
      } else {
        $('.class-of-element').append('.desktop-section');
      }
    
    });

    You could also load the element in both places, and use CSS Media Queries to hide/show the element. For example:

    .mobile-class {
        display: none;
    }
    
    .desktop-class {
        display: flex;
    }
    
    
    @media only screen and (max-width: 768px) {
      .mobile-class {
          display: flex;
      }
    
      .desktop-class {
          display: none;
      }
    }
    

    If you can provide more context for what you're trying to do there may be other suggestions as well, but this hopefully gets you thinking about how you want to tackle this issue.