Switch between webpage design for different devices (mobile/desktop) using javascript, jquery, and bootstrap

I am currently working on a webpage that contains various html elements with bootstrap classes applied to them.

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

My goal is to implement a button that, when clicked, will toggle the viewport/layout changes of these divs on the webpage. Upon clicking the button, I need to be able to instantly see the layout change in real-time, displaying "col-xs-12" for mobile view and "col-lg-4" for laptop view. However, I am unsure which specific CSS or Bootstrap property I should be utilizing for this functionality.

Any guidance or assistance on this matter would be greatly appreciated.

EDIT - Use case - I am providing a platform for users to edit CSS and classes. I aim to include a toggle button so users can visualize how their elements will appear in both laptop and mobile views.

Answer №1

To begin, you can set up an iframe and load your website's content into it asynchronously.

<iframe id="media-simulator" class="embed-responsive-item"></iframe>

<script>
$(document).ready(function(){
    $('#media-simulator').load('/includes/main-page.html');
})
<script>

Bootstrap's media queries are responsive to the width of the iframe. This allows you to define specific widths in your CSS and then add these classes to the iframe using jQuery:

.xs {
  width: 375px;
}

.sm {
   width: 576px
}

.md {
   width: 768px
}

.lg { 
   width: 992px
}

.xl {
   width: 1200px
}

Add click handlers to your buttons to toggle the desired class. For example, here is an event handler to toggle the mobile preview:

$('.button-xs').click(function() {
  $('#media-simulator').removeClass('sm');
  $('#media-simulator').removeClass('md');
  $('#media-simulator').removeClass('lg');
  $('#media-simulator').removeClass('xl');

  $('#media-simulator').addClass('xs');
})

Answer №2

In a previous discussion, it was mentioned that media queries are limited to detecting the device width and not the width of an element.

To overcome this limitation, one could consider using a JavaScript shim such as the CSS Element Queries polyfill, which extends support for element-based media queries in modern browsers (IE7+).

According to the official documentation of the polyfill, CSS Element Queries enables defining media queries based on both window size and the size of specific elements, without sacrificing performance due to its event-based implementation.


For a demonstration, refer to this JSFiddle or review the following Code Snippet showcasing how the polyfill introduces new element attributes with the ~= attribute selector on DOM elements based on your CSS and the dimensions of the elements:

/* 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>Enhanced Element Responsiveness!</h2>
</div>

Answer №3

If you are utilizing bootstrap classes, the design should automatically adjust based on the browser or screen size. However, if you specifically want a button to trigger a layout change, you can achieve this by toggling classes using JavaScript.

To modify the element(s) you wish to change, assign them a unique identifier such as an id or class for easy selection. Apply only one of the classes initially (e.g., just col-lg-4), then use JavaScript to toggle between classes. By creating a button that calls a function, you can successfully implement this functionality.

<button onclick='changeLayout()'>Change Layout</button>

function changeLayout() {
  var myDiv = document.getElementById('myDiv');
  myDiv.classList.toggle('col-lg-4');
  myDiv.classList.toggle('col-xs-12');
}

For multiple elements, you will need to make some adjustments while following the same approach.

I hope this explanation proves helpful! If I have misunderstood your query, I apologize and would appreciate further clarification.

Answer №4

Have you considered using a toggle simulator for changing the website's view? Give this a try and see if it works for you: fiddle

Here is the HTML code:

<button type="button" id="toggle_btn">
   Toggle Viewport
</button>
<span id="span">Desktop View</span>
<hr />
<section class="iframe_holder">
  <iframe src="https://getbootstrap.com/" id="dup_viewPort"></iframe>
</section>

And here is the JS code:

var isToggled = false;
$('#toggle_btn').click(function() {
  if (!isToggled) {
    $('#dup_viewPort').animate({
      width: '375px'
    }, function() {
      isToggled = true;
      $('#span').text('Mobile View');
    });
  } else {
    $('#dup_viewPort').animate({
      width: '100%'
    }, function() {
      isToggled = false;
      $('#span').text('Desktop View');
    });
  }
})

Lastly, the CSS code:

#dup_viewPort {
  width: 100%;
  position: relative;
  height: 100%;
  border: 0;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide to creating a clickable div

Having an issue with around 200 clickable buttons on my website, all designed the same: <div> <asp:hyperlink> //or LinkButton </div> The background-style of the button is within the Div and the text of the button is in Hyperlink / LinkB ...

The callback function in Ajax is returning an undefined response, causing an Uncaught Reference

Code: query = "http://localhost:8080/working_login.php?name=" + name + "&password=" + pass; console.log(query); $.ajax({ type: "GET", url: query, dataType: "script", success: function(data){ console.log(data); con ...

Ensuring consistent column height in HTML Tables

Hey there, I'm just starting out with CSS and I have a question about table design. I have three separate tables below and I want to ensure that all the columns in each table are of equal height. Is there an easy way to achieve this? Any suggestions o ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

What is the best way to compare two times in the hh:mm AM/PM format?

I need to handle times in the format of hh:mm AM/PM generated by a specific plugin, and perform comparisons on them using jQuery/javascript. When a user manually inputs a time, I require the text in the textbox to automatically adjust to hh:mm AM/PM with ...

What is the process for assigning an item from the result list to the parent Div tag of the current object?

I've been working on a function to insert the number of Facebook Likes into a Div tag. The script I have so far can extract the URL from a Div tag inside another Div named 'entry'. Then, using the .getJSON() method, it fetches the Facebook l ...

Collapsing table row in Bootstrap upon button click within the same row

The snippet showcases a basic table with one row containing a button group. Upon clicking the 'main' button (the reset button), the following table row will appear. This behavior is intended only when clicking on the table row itself, not the but ...

The Bootstrap dropdown menu is cut off and not fully visible on mobile devices

I am experiencing an issue with the mobile version of a website where the dropdown menu is not fully visible due to the position of a specific menu item and the number of items in the dropdown. https://i.sstatic.net/HmXeq.png The image below shows how I ...

What could be causing the JSF ajax status success to fail in Chrome?

Whenever I trigger an action in my ManagedBean, I also initiate a JavaScript function via JSF ajax to display a loading popup while the action is being processed. This functionality works flawlessly in Firefox, however, it seems to encounter issues in Chro ...

Send form using AJAX, then insert the data into a DIV once it has been validated by jQuery

Hello everyone, I'm facing an issue with the code below: $(document).ready(function() { $("#create_review").validate(); $("#submit_review_link").click(function() { if ($("#create_review").valid()) { $("#create_review").submit(fu ...

Trouble with using AJAX to transfer a JavaScript variable to a PHP file

I need assistance in sending a JavaScript variable to a PHP file for displaying comments on a webpage. While I have successfully sent the JS variable to other PHP files, I'm facing issues when trying to do the same with the comment-list.php file. It ...

Having trouble targeting a div with jQuery

Is it possible to target a specific div within an unordered list and list items? I'm having trouble with it. Here is the HTML code: <ul class="grid"> <div id='categoria' cat='web'></div> <li id=' ...

Progress to the following pages after each page remains inactive for 3 seconds

Is it possible for someone to assist me in creating a script that automatically switches between pages when the page is idle for 3 seconds? My current setup only allows for movement from one page to another, but I have 4 pages that I would like this featur ...

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

What is the best way to implement the nth:child selector in conjunction with the each function for handling JSON data in

Here is the HTML code I have written: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Flickr Feed</title> <link href="../_css/site.css" rel="stylesheet"> <link rel="stylesheet" type= ...

Using JQuery to parse data in a $.post request

My goal is to dynamically populate textboxes using JQuery based on an array sent from an external PHP file through json_encode(array). The chosen option in a select box determines which value is sent to the PHP file. Despite my efforts to debug using tools ...

Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link. The issue at hand is that the newly created div does not appear in the desired location, but ...

Capture the onclick attribute with jQuery and then reapply it

I am facing a challenge with a page that has several calendars composed of HTML tables where each day is represented by a td. The td elements have an onClick attribute which I need to manipulate using jQuery. Specifically, I need to remove the onClick attr ...

Columns with adjustable widths

I am looking to create a layout with 3 columns (which may change, could be up to 4) that are all flexible width and fill the screen. Does anyone know if this is possible using CSS? Basically, I want three blocks lined up horizontally that take up the enti ...