Adjust image loading according to screen dimensions

I am working on HTML code that currently displays an image. The code looks like this:

<div>
     <img id="wm01" alt="PP" title="PP" u="image" src="theImages/wm01.jpg" />
</div>

My goal is to show a different image based on the screen size. To start, I use CSS to hide the image:

#wm01 {
    display: none;
}

Next, in the BODY of my document, I add the following JavaScript code:

var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;

if (x<568) {
    //alert(x);
    document.getElementById("wm01").src="theImages/wm01_app.jpg";
    document.getElementById("wm01").style.display = "block";
}
else {
    document.getElementById("wm01").src="theImages/wm01.jpg";
    document.getElementById("wm01").style.display = "block";
}

Unfortunately, the image is not showing up on any screen size. How can I troubleshoot and fix this issue?

Answer №1

It has not been suggested to utilize the <picture> element yet.

The <picture> element offers the advantage of being able to specify different images for various window sizes.

For instance:

<picture>
    <source srcset="some-bigger.png" media="(min-width: 500px)">
    <img src="some.png" alt="Some picture">
</picture>

In your case, it would look like this:

<picture>
    <source srcset="theImages/wm01_app.jpg" media="(min-width: 568px)">
    <img src="theImages/wm01.jpg" alt="PP">
</picture>

This indicates that theImages/wm01_app.jpg should be used when the device width is at least 568px. Otherwise, the default <img> source will be used.

Answer №2

Have you considered utilizing the srcset and sizes attributes of the <img>

<img srcset="tiger-320w.jpg 320w,
             tiger-480w.jpg 480w,
             tiger-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="tiger-800w.jpg" alt="Bengal tiger">

For further information, check out Responsive_images

This feature is supported by all major browsers

Answer №3

If you want to ensure compatibility with browsers that do not support media queries, consider using CSS media query first and then JavaScript as a fallback option. In this example, the image is changed when the maximum width reaches 850px.

CSS:

/* Media query to transform layout for devices with a maximum width of 850px */
#wm01 { 
     background:url(images/large_image.png);
     width:100px;
     height:50px;
}
@media screen and (max-width:850px) {
     #wm01 {
         background:url(images/smaller_image.png);
     }
}

JS/JQuery:

var width = $(window).width();
if (width >= 850) {
    $('#wm01').addClass('largeImageClass');
} else {
    $('#wm01').addClass('smallImageClass');
}

HTML:

<div id="wm01" alt="PP" title="PP" u="image" /><!--comment for legacy browser --></div>
<img id="wm01" alt="PP" title="PP" u="image" />

Answer №5

Although there have been suggestions for alternative methods to address the issue of multiple images, your proposed solution highlights a common mistake - attempting to set the src attribute of an image before the DOM is fully loaded. To ensure everything is properly loaded, it's important to utilize window.onload. Consider updating your code as follows:

var win = window,
doc = document,
html = doc.documentElement,
body = doc.getElementsByTagName('body')[0],
width = win.innerWidth || html.clientWidth || body.clientWidth,
height = win.innerHeight || html.clientHeight || body.clientHeight;

// Onload function:
window.onload = function(){
    if (width < 568) {
        doc.getElementById("wm01").src = "theImages/wm01_app.jpg";
        doc.getElementById("wm01").style.display = "block";
    }
    else {
        doc.getElementById("wm01").src = "theImages/wm01.jpg";
        doc.getElementById("wm01").style.display = "block";
    }
};

Answer №6

I implemented this code on my website and it worked flawlessly for me.

HTML

<figure class="picture"></figure>

JAVASCRIPT / JQUERY

$(document).ready(function(){
    var screenWidth = window.innerWidth;
    if(screenWidth <= 650){
      $(".picture").html("<img src='images-min.jpg'/>")
    }
    else if(screenWidth > 650 && screenWidth <=1300){
      $(".picture").html("<img src='images-med.jpg'/>")
    }
    else{
      $(".picture").html("<img src='images-big.jpg'/>")
    }
});

In this scenario, I utilized three different sizes of images.

Answer №7

Reduce image size and display a background image using a media query.

Please keep in mind that you need to be aware of the dimensions of the replacement image for this method.

Check out the Fiddle

<img id="wm01" alt="PP" title="PP" u="image" src="theImages/wm01.jpg" />

@media screen and (max-width:568px) {
  #wm01 {
    background: url("theImages/wm01_app.jpg") no-repeat 0 0;
    height: 0;
    width: 0;
    padding-bottom: 300px; /* replace with height of wm01_app.jpg */
    padding-right: 300px; /* replace with width of wm01_app.jpg */
  }
}

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

Guide for implementing a one-line if statement in Javascript

I am aiming to assign a class using a single-line if statement as outlined in this source. Currently, I am utilizing Material-UI and attempting to specify a class. Therefore, I would like to implement this approach: if(condition) expression <Typogr ...

Sending information from Axios to Danfo using NextJs is seamless and efficient

I am currently developing a NextJs page where I have incorporated axios along with useState and useEffect to fetch JSON data from a web API and store it in a state called 'apiData'. .then((res) => { setApiData(res.data.Projects); conso ...

What is the right height and width to use in CSS?

I find it challenging to decide when to use rem, em, px, or % in web design. Although I know the definitions of each unit, I struggle with knowing the appropriate situations to utilize them. What guidelines should I follow to determine which one to use? ...

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

What is the best way to choose the final XHTML <span> tag with a specific class using XPath?

My target XHTML document structure is as follows: <html> <head> </head> <body> <span class="boris"> </span> <span class="boris"> </span> <span class="johnson"> </span> </body> </html> ...

StopPropagation() method in Ng-class not functioning properly in Angular for parent element

I am facing an issue with 2 nested ng-repeats. The parent one is supposed to add a class based on ng-click, but even when I click the child, it still triggers when I don't want it to. <div class="add-filter-tags" data-filter="{{f1}}" ng-class="{&a ...

Using Jquery to bind events for selecting focus in and out

There seems to be an issue with binding jQuery events to a select element. The desired behavior is for the .focus class to be added when the select is clicked. However, the logic breaks when an option is selected from the dropdown. See it in action here: ...

Is JSON.stringify failing to function correctly in Mozilla Firefox?

Currently, I am attempting to convert an object into a string in javascript. After stringifying the object, I have noticed some discrepancies between different browsers. {"jobTypeArray":"[CONTRACT -W2]"} In Firefox and Chrome, the values appear as follow ...

What is the best way to fill in predetermined HTML with information using jQuery?

Currently, I am working with several ajax forms that allow me to add rows of data dynamically using ajax. While the form submission is functioning correctly, I am having trouble figuring out the best way to append the newly inserted data into the database. ...

What are some key considerations for creating a website that is optimized for printing?

I am working on creating a website filled with content that I want to optimize for printing. My goal is to have the content easily printable without any unnecessary elements like navigation or advertisements. To achieve this, I am considering using two sep ...

Containerized chatboxes with improved stability

Within the div labeled chatbox-container, there are two chatboxes that have been positioned to float: right with a margin-right: 15px. .chatbox-container { position: fixed; z-index: 1; right: 0; left: 0; bottom: 0; } An issue arises ...

Is there a way to format wrapped lines with indentation in an unordered list?

Is there a way to indent the wrapped lines of text in an unordered list? The current layout is not quite what I want, as shown in the first image below. Ideally, I would like it to look more like the second image. I attempted to use margin-left: 56px; and ...

Do I have to include the sizes attribute when using w-descriptors in srcset?

After reading several articles discussing the use of srcset for device-pixel-density adjustments and art direction, I have come to a few conclusions: The State of Responsive Images in 2015 by Paddi Macdonnell srcset Part 2: The W descriptor and sizes att ...

Ways to incorporate additional fields into your html/php form

Is there a way to increase the number of fields in my basic form? I want to include fields like username, email, subject, and more. Just looking to add additional fields to the form. <!DOCTYPE html> <html> <head> <title>Storing Fo ...

Only refresh the content when there are updates from the ajax call

Currently, I am populating an HTML table with data retrieved through an AJAX request. The AJAX call is made at regular intervals of X seconds. I am specifically looking for a way to update the table only when the new data fetched from the AJAX call diffe ...

What are the disadvantages of using getBoundingClientRect() in ReactJS?

I recently incorporated the getBoundingClientRect() method into my project. However, a fellow React developer expressed concerns about its browser compatibility. In theory, shouldn't Webpack or Babel handle such compatibility issues? ...

Is React the ideal choice for implementing a shared state subscription mechanism in your project?

Trying to determine if this falls under the "pub/sub" pattern or a variation of it. The goal is to establish a shared state where different components can subscribe to it and only receive updates when the state changes. const useForceUpdate = () => useR ...

NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept ...

Tips for inserting information into HTML components in JSP

Hey everyone, I'm diving into JSP for the first time and I'm trying to wrap my head around how to display data from an ArrayList in my HTML. Can someone help me out? I'm thinking of doing something like this: <article> <p>< ...

Attempting to modify a singular document within mongodb by leveraging node.js

const modifyTask = async (req, res) => { const { id } = req.params; let update = {}; if (req.body.taskTitle) update.taskTitle = req.body.taskTitle; if (req.body.taskContent) update.taskContent = req.body.taskContent; if (req.body.role) update. ...