Check out the CSS media query for screens with a maximum width on larger devices

Is there a way to preview a specific div and see how it appears on mobile devices? The HTML code for the div is obtained from an external source, like this:

var external_html='<div>Responsive div</div>' +
   '<style>@media screen(max-width:360) {{color:blue}}</style>')
var element=$(external_html)
.appendTo(document.body)

Even after using $(element).width(300), I still see the desktop version. Is there a way to view how it looks on different devices?

In simpler terms: How can I simulate CSS media queries for a single element within the document?

Just to note: I am aware of using IFrames for this purpose, but would prefer to avoid them.


HTML Version of the question:

<div style=width:250px>
   It will be black
</div>
<div style=width:190px>
   Ideally, I want it to appear in blue. However, it remains black
</div>

<style>
    div.preview (max-width:200px){
        // This style should only apply to the second div
     color:blue
    }
</style>

Reasoning behind this: With Angular, I'm developing a WYSIWYG directive that requires support for responsive layouts. I aim to allow end-users to visualize real-time mobile views. How can I achieve this emulation of mobile devices within the directive? Thank you

Answer №1

Looks like I'll have to figure this out on my own since there are no answers...

Check out my JSFiddle demo here: https://jsfiddle.net/khuj1ph5/2

I've created a handy function called addTo:

function addTo(target, html, style, deviceWidth){

Here's what the parameters mean:

target - the target DOM element
html - the HTML text to append to the DOM
style - the CSS style to apply to the HTML
deviceWidth - the width of the device to display

*How does it work?

The function parses the CSS and adjusts the mediaText so that it looks like the original design on the specified device.

This function is great for responsive CSS designs.

For example, using this code will only display the message for on_small:

var mySize = 300;
var externalHtml = '<div class=on_big>On Big</div><div class=on_small>On small</div>';
var externalStyle = '.on_big,.on_small{display:none} @media   (min-width:500px) {.on_big{display:block;}} @media   (max-width:500px) {.on_small{display:block;}}';

addTo(document.body, externalHtml, externalStyle, mySize);

The Code: https://jsfiddle.net/khuj1ph5/2

To test it out, just change the value of mySize from 300 to 600.

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

Tips for transferring information in JavaScript games

While browsing an HTML-based website, I am able to send POST and GET requests. However, in a JavaScript game like agar.io, how can similar actions be performed? Specifically, when playing a popular game like agar.io, how is my game state (such as positio ...

What is the method for triggering a mouse event when selecting rows in a table?

Is there a way to generate a mouse event when selecting multiple rows? I am looking to capture this event and send it to another destination. Appreciate any help! Best regards ...

I am experiencing issues with my drag and drop feature not functioning properly

I am looking to reposition my #timebase1 div within the draghere div. Currently, it only moves the start of the div, but I would like to be able to drop it anywhere inside the draghere div. function handleDrag(e) { var id = e.id; ...

I encountered an issue with loading an array from session storage in Java Script

I am struggling to restore and reuse a created array in HTML. I attempted using JSON, but it was not successful for me. In the code below, I am attempting to reload items that were previously stored in an array on another page. However, when I try to loa ...

Align the center element vertically on a website with a Bootstrap 4 navigation bar

I am trying to vertically center an element on the page. It works fine until I add a Navbar, which causes the element to be centered with an offset from the height of the Navbar. How can I center the content container vertically while accounting for the Na ...

Use CSS to style an unordered list into a dropdown menu

Would it be feasible to style an unordered list to resemble a dropdown menu using only CSS, without relying on external libraries like jQuery or MooTools? Appreciate your insights. Warm regards, Neil. ...

Implementing automatic dark mode activation during nighttime with jQuery or JavaScript

I'm looking to implement an automatic dark mode feature on my website that switches on at night and off during the day or morning. Currently, my website has a dark mode toggle code that allows users to switch between dark and light modes using local ...

Issue with Telerik JavaScript when navigating away from page

While working on my Asp.net web application, I encountered a JavaScript error when trying to unload a page: An issue arose with setting the value of the property '_events': Object is null or undefined This problem occurred after merging/combi ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

If a user enters an incorrect path, the goal is to automatically redirect them to the homepage while displaying the correct URL in AngularJS

When the URL is manually edited, the webpage displays the same content with a different URL structure. For instance, http://www.example.com/# and http://www.example.com/#/abc both show identical content. I would like to implement a redirect for any edite ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

What is the process for running "node server.js" within codelab?

I am currently going through a codelab tutorial on Bitbucket at this link After installing node.js for the first time, I encountered an error when trying to run the server.js file: node server.js The error message "node: Command not found" appeared even ...

Minimizing the gap between icon and label text

I have a React form that I need help with. The issue is that I want to reduce the space between the list icon and the label. Here is the CSS I am using: .form__container { display: flex; flex-wrap: wrap; } .form__container input { color: rgb(115, 0, ...

Combining values and eliminating duplicates from an external API: A step-by-step guide

My API provides soccer game results in this format: results:[ { Group:"A" Home: "Fc Barcelona", Away: "Fc Porto" Score: { Home: 0, Away: 0 }, { Group:"A" Home: "AC Milan", Away: "Fc Barcelona" Score: { Home: 0, Away: 1 }, { Group:"A" Home: "FC Barcelona" ...

Updating REST API: Sending a PUT request without requiring all data to be included in json format

I have a controller set up for updating user data. The controller can accept up to 4 values. I am wondering if it is possible to only update the name field when sending data to this route, leaving the rest of the fields unchanged (and not empty). Should ...

Enhance the user experience with a personalized video player interface

I am facing difficulty in creating a responsive video with custom controls. While I understand that using a <figure></figure> element and setting the width to 100% makes the video responsive, I am struggling with making the progress bar also r ...

How can I bind an event for changing innerHTML in Angular 2?

Is there a way to implement something similar to this: <div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div> Currently, I have a variable content that is updated by a service fetching a string from my express server. The content ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Guide on resolving the issue of disabled button's tooltip not appearing upon being hovered over

I have a button that looks like this: <a data-toggle="tab" href="#part4" class="btn btn-info tabcontrol mainbutton col-2 offset-8 disabled" id="part3to4" title="Please acknowledge the checkbox before going next" data-toggle="tooltip" data-html="true" d ...

Develop a custom input field feature that utilizes both JavaScript and CSS

I really appreciate the feature that allows me to resize the textarea by simply clicking and dragging on the slanted lines in the lower right hand corner. However, I am looking for a way to apply CSS styles to text which is not possible with a textarea. ...