Adjust image source based on media query (CSS or JavaScript)

Is there a way to update the image src based on a media query with a maximum width of 515px? I'm considering using JavaScript, jQuery, or even AngularJS if there is an event equivalent to a CSS media query that can achieve this.

I want to have different images for different screen sizes to optimize loading times and reduce file sizes. For example, loading a smaller 50 KB image on mobile devices instead of a larger 700 KB one.

If you need any additional code or information, please let me know in the comments so I can provide it.

Note: The solution provided in this answer for the question How to use a lower resolution image for mobile uses the HTML5 picture element instead of a CSS or jQuery media query, which is also a viable option.

Answer №1

One way to approach this is by utilizing JavaScript to dynamically set the image source based on the window width.

$(document).ready(function() {
     if($(window).width() > 515) {
         $("#img").attr("src", "large.png");
     } else {
         $("#img").attr("src", "small.png");
     }
}); 

For mobile devices, it's important to also consider the width during orientation changes.

If you prefer not to use the img tag, background images can be managed through CSS media queries.

Answer №2

Here is a suggestion that might be useful for you:

<img src="" data-mobile="mobile-version-url" data-desktop="desktop-version-url" />

You can utilize some JavaScript or jQuery to dynamically set the image source based on the window's width.

For instance, below is a sample jQuery script demonstrating this approach:

$(document).ready(function() {
    var device = $(window).innerWidth() > 515 ? "desktop" : "mobile";
    $("img").each(function() {
        $(this).attr("src", $(this).data(device));
    });
});

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

Displays a white screen once the code is executed

I am attempting to retrieve data from a database, and it appears that I am fetching the information correctly. However, when I run the code, I am presented with a blank page. Since I am new to PHP and MySQL, I would appreciate some guidance on this issue ...

Exploring the capabilities of Jasmine 2.0 by testing an AngularJS factory method that returns a promise

When attempting to test a function that returns a promise, I encounter the following error: "Error: Timeout - Async callback was not invoked within the timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. " The specification I am using is as follo ...

Having trouble viewing the page of a new package you published on the NPM Website?

Today, I officially released an NPM package called jhp-serve. It can be easily installed using npm install or run with npx. You can even find it in the search results here: https://www.npmjs.com/search?q=jhp. However, when attempting to view its page by cl ...

Acquiring data from an API response in JSON format using JavaScript

Utilizing a parse.com API server, I have successfully established communication in JavaScript through AJAX. The output from the response is being logged into the browser console with the following code: $.ajax(settings).done(function(response) { ...

jQuery modal fails to display

I am currently experiencing an issue with my jQuery dialog that is not displaying after clicking a radio button. Previously, the dialog was showing properly, but after implementing some script for submitting from the dialog, it stopped showing up when th ...

Using Selenium Webdriver to simulate pressing ‘ctrl + t’ for opening a new tab in Javascript

I have been utilizing Selenium Webdriver to conduct testing on a web application that is currently undergoing development. Despite having developed multiple tests already, I am facing challenges in attempting to open new tabs within the window controlled b ...

The dynamic functionality of the Bootstrap React Modal Component seems to be malfunctioning

I'm encountering an issue with React Bootstrap. I'm using the map function in JavaScript to iterate through admins. While all values outside the modal display correctly from the admins array, inside the modal only one standard object from the arr ...

What could be causing only certain portions of my CSS to be applied?

I've been struggling to get rid of the gray border around the SIGN UP button in the tbody section. I've tried applying classes (along with the ID) and using pseudo classes like :4th-child {border:none}, but nothing seems to work. The only solutio ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

Inheritance best practices for node.js applications

In C#, the concept of inheritance can be easily demonstrated through classes like Animal and Dog. class Animal { string name; public Animal() { } } class Dog : Animal { public Dog() : base() { this.name = "Dog"; } } When working ...

Script for migrating MongoDB attributes to an array

I am in the process of creating a database migration, and the current structure is as follows: { "site" : { "name" : "siteName1" }, "subStages" : [ "subStage1", "s ...

Using either Java or Groovy, iterate through a hashmap and showcase an HTML table within a Velocity template

Just a heads up: Some users may have trouble reading code comments. For the record, this is not related to any homework assignment. I'm attempting to combine HTML and a hashmap for the first time. Despite searching for explanations online, nothing see ...

The GET method is designed to automatically eliminate any trailing whitespace in the

Whenever I utilize the GET method to transmit a text to the server, like 'abc ', I notice that the whitespace characters at the end are always removed. As a result, the server receives 'abc' instead of 'abc ' My question is w ...

Efficient AJAX validation using PHP and JavaScript

I am currently working on a small website project that requires User registration functionality. One key aspect is ensuring that the system prevents users from registering with usernames that are already in use. Most modern websites employ AJAX to verify ...

Understanding the res.render method in JavaScript can be a bit tricky at first

In my spare time, I have been immersing myself in coding lessons and have encountered some puzzling aspects of the code: Firstly, there is a confusion surrounding the action attribute in HTML Secondly, this particular piece of code is causing me some b ...

Display the element when the input is in focus

I'm currently working on optimizing a code snippet. The idea is to display a paragraph tag showing the characters remaining when you focus on a textarea. Here's what I have so far: import React, { Component } from "react"; class Idea extends Co ...

What is the best way to use CSS to evenly lay out a group of dynamically generated buttons?

My Vue-generated buttons need to be evenly laid out on the bottom of the page, with equal space on the left and right. The mdui button style I am using has fixed width and height, so I have to decide between a single row for fewer buttons (less than three ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

Is there a way to find a substring that ends precisely at the end of a string?

Looking to rename a file, the name is: Planet.Earth.01.From.Pole.to.Pole.2006.1080p.HDDVD.x264.anoXmous_.mp4 I want to remove everything starting from 2006 onwards. I considered using JavaScript string methods to find the index of the unnecessary part an ...

Tips for preventing special characters from being entered into a Kendo grid input column

Is there a way to prevent users from entering special characters into the description column of my Kendo grid? The column field setup is as follows: { field : "myDesc", width : 200, title : "My Description"} I have attempted the following approach so far ...