Search code examples
jquerycssresponsive-designbootstrap-4viewport

Toggle between webpage layout (phone/laptop) with javascript, jquery, bootstrap


I have a webpage with certain html elements with bootstrap classes.

<div class="col-xs-12 col-lg-4"></div>

I want to give a button when clicked, should toggle viewport/layout change of divs on webpage. On click of that button, I should be able to see realtime change of layout and bootstrap trigger "col-xs-12" for mobile view and "col-lg-4" for laptop view. I dont know which css or bootstrap or html property I am looking for.

Any help will be much appreciated.

EDIT - Use case - I am giving a screen for user to edit CSS and classes. I want to give toggle button to user, so that he can see how his elements will look like in laptop view and mobile view.


Solution

  • As discussed here, media queries can only detect the device width and not an element's width.

    Your best bet would be to use a JavaScript shim like the CSS Element Queries polyfill that adds support for element based media-queries to all new browsers (IE7+).

    As stated in the polyfill's official Docs, CSS Element Queries not only allows you to define media-queries based on window-size but also adds 'media-queries' functionality depending on element (any selector supported) size while not causing performance lags due to event based implementation.


    Check this JSFiddle or the Code Snippet below to see how this polyfill adds new element attributes with the ~= attribute selector on the DOM element depending on your actual CSS and element's dimension:

    /* CSS */
    
    .widget-name h2 {
        font-size: 12px;
    }
    
    .widget-name[min-width~="400px"] h2 {
        font-size: 18px;
    }
    
    .widget-name[min-width~="600px"] h2 {
        padding: 55px;
        text-align: center;
        font-size: 24px;
    }
    
    .widget-name[min-width~="700px"] h2 {
        font-size: 34px;
        color: red;
    }
    <!-- HTML -->
    
    <script src="https://combinatronics.com/marcj/css-element-queries/master/src/ResizeSensor.js"></script>
    <script src="https://combinatronics.com/marcj/css-element-queries/master/src/ElementQueries.js"></script>
    
    <div class="widget-name">
      <h2>Element responsiveness FTW!</h2>
    </div>