Implementing the @media rule using Javascript

I'm trying to use JavaScript to add an image dynamically, but I want to remove it when the viewport is 600px or wider.

This is my approach so far:

var img = document.createElement('img');
// (imagine here all the other fields being defined).
img.style='My @media rule here';

Unfortunately, this method didn't work. Is there a different way I should be attempting this?

Answer №1

To dynamically add an image and apply a CSS class to it, you can follow these steps:

JavaScript:

var img = document.createElement('img');
img.className = "dynamicImage";
img.src = "path/to/image.jpg";

CSS style:

@media screen and (min-width: 600px) {
    .dynamicImage {
        display: none;
    }
}

See the working example here: https://jsfiddle.net/abc123xyz/2/

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

The customized styling for Material Angular does not seem to properly apply to <md-card> elements within ui-views

I am trying to achieve a specific effect on the ui-views <md-card id="sidebar" flex="20" class="sche-card" layout-padding="true"> <div ui-view="card" autoscroll="false"></div> </md-card> However, I am facing an issue where the car ...

How can we deliver pure JS, HTML, and CSS content without relying on static HTML pages?

Looking to create a fast app prototype without using React or Vue? I'd like to avoid simply making an html and js file imported within it. Can npm packages, SCSS be used while programming vanilla Javascript minus a framework? ...

Meta tag settings for iOS web applications fail to function

I am currently working on a website locally using a MAMP stack. One issue I am facing is that none of the necessary meta tags for configuring a website as an iOS standalone web application seem to be working in my header, which is wrapped in a php template ...

Ensuring the accuracy of user input in JavaScript, even after fixing a mistake and submitting again, will not cause the code to exit the else clause

I am currently working on a coupon code field that needs to accept a specific set of coupon keys. Below is the code I have written for validation. If a user enters an invalid key at first, they receive an alert saying "Invalid Key." However, if they corr ...

View cards from a restricted Trello board without requiring visitors to have a Trello account or to authorize through a popup

I have a company with ongoing projects listed on a private Trello board. We are interested in showcasing these projects on our website in real-time by connecting to the board. After implementing this example, I can successfully retrieve and display the ca ...

Only make an AJAX request for suggestions with jQuery Autocomplete if the item does not match any data from the previous request

I am currently working with jQuery Autocomplete functionality. The issue I am facing is that it triggers an AJAX request every time a key is pressed, which is not desirable. Ideally, if the data from a previous AJAX request already matches the search query ...

JSON Generator's date formatting convention

One method I use to create a JSON object is through JSON-GENERATOR I prefer the date to be formatted like this: 2017-12-31 [ '{{repeat(5, 7)}}', { equityPriceList: [ { date:'{{date(new Date(1970, 0, 1), new Date(),[DD ...

The proper way to implement global scripts in Next.js

I am currently working on implementing a global fade-in animation for all components in my application. By adding the className "fadeIn" to each element and setting the default opacity to 0, I then utilize JavaScript to change it to 1 when the element is v ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

Express server continuously returning 404 error for all requests originating from the index page

Experiencing a challenge with the express/gulpfile.js code. Express can serve the index.html without issue, but it fails to navigate to the lib/* directory resulting in all requests for resources at the top of my index.html returning 404 errors. Browser-s ...

Tips for using Python to capture specific HTML snippets

Here is a Python code snippet that I am working on: def parseAddressInfo(text): text = re.sub('\t', '', text) text = re.sub('\n', '', text) blocks = re.findall('<div class="result-box" ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...

Is there a way to send me the result of the radio input (Yes/No) via email?

Is it feasible to send the results of a radio input (Yes/No) back to my email directly using HTML, CSS, and Javascript? ...

Divs sliding out of alignment

I am experiencing an issue with the scrolling behavior of a wrapper div that contains two nested divs. Specifically, when I scroll the wrapper horizontally on Android devices, the header section and content section seem to be out of sync and there is a not ...

The offset value was inconsistent in the desktop version of Firefox

Could you take a look at my code on the fiddle link, Here is the code snippet: <body> <div id="content" style="width:400px; height:110px;"> <svg id="circle" height="300" width="300"> <circle cx="150" cy="150" r="40" st ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...

What is the best way to send an array of grouped data to a table

Here's how I organized the array: { "2023-10-01": [ { "emp_id": 1, "name": "Aruna", "code": "DO", "date": "2023-10-01" }, { &qu ...

Sending data from Flask to Ajax

Upon accessing the main page, my Flask application generates a base Jinja template with specific elements: <div><span id="var_1">{{ var1|safe }}</span></div> <div><span id="var_2">{{ var2|safe }}</span></div> ...

The request to http://localhost:5000/error resulted in a 404 (Not Found) error message. I encountered difficulties connecting

When attempting to retrieve information about a product from Amazon using their productId with Express.js and ScraperAPI, an error is encountered: Error message: "{name: "RequestError", message: "Error: Invalid URI "${baseUrl}&url=https://www.amazon.com/d ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...