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

obtaining Json format from an array: a comprehensive guide

Hey there, I am looking to convert my array into JSON format. Currently, my array structure looks like this: Array[0] abc: Array[1] 0: "English" length: 1 abc1: Array[2] 0: "English" 1: "Urdu" length: 2 Here is the structure that I want in JSON using Jav ...

Struggling to get the Ant design button to launch an external link in a new tab using React and NextJS

I have an Ant button set up like this: <Button style={{ borderRadius: '0.5rem' }} type="default" target="_blank" ...

I'm having trouble understanding why this code is causing confusion for the user's selection during a specific part of the execution. I can't seem

In this memory game, event listeners respond to user input after a sequence of colored divs change color to appear illuminated. The expected behavior is that once the user clicks on the correct div in the right order, the sequence restarts with an additi ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

The suspense fallback function seems to be missing in NextJS 13

I'm in the process of creating an application to demonstrate the functionality of Suspense in Nextjs 13. However, I'm encountering an issue where the Suspense fallback is not appearing during loading. Below is the code for page.js import React, ...

Sending data from Node.JS to an HTML document

Currently, I am working on parsing an array fetched from an API using Node.js. My goal is to pass this array as a parameter to an HTML file in order to plot some points on a map based on the API data. Despite searching through various answers, none of them ...

Enclose Angular $resource requests that do not return POST data

Currently, I am working on enhancing my $resource requests by implementing a straightforward wrapper. The primary objective is to incorporate some logic before the request is actually sent. For guidance, I referred to an informative article authored by Nil ...

Issue with JavaScript JSON.parse converting string values to Infinity

Does anyone have an explanation for this peculiar behavior I encountered while using the JSON.parse() function in Javascript? Normally, when you pass a string to it, it should generate an error. For example, JSON.parse("5ffc58ed1662010012d45b30" ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

Set a variable to contain a specific scope in JavaScript

I'm struggling to pass user input from a text box stored in $scope to a firebase query. Here's the code I have so far: $scope.array = []; $scope.addListItem = function(quote){ $scope.array.unshift(quote); console.log(quote) this.customQuote = ...

Ways to implement border spacing using CSS

Here's a snippet of the code I've been working on: HTML: <html> <body> <div id="article"> <h1>TITLE</h1> <p>text</p> </div> </body> </html> CSS: #article { colo ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...

Clickability issue with searchbar results caused by onBlur event

My searchbar functionality includes showing results in a dropdown list when the user searches. However, I am facing an issue with the onBlur event that changes the display of the list to none when the user clicks away from the search box. The problem aris ...

Display a modal popup form in ReactJS when a particular key is pressed

As a beginner in ReactJS, I am currently developing the frontend of a web application that requires multiple modal dialogues to be displayed based on specific key combinations. To achieve this functionality, I plan to utilize JQuery-UI for the modal dialog ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Error in content policy for CSS in Stripe Checkout

I am currently attempting to integrate Stripe Checkout into my Ionic App. I have created a Directive that injects the form into my content view, however, upon execution, the CSS fails due to a content policy violation: checkout.js:2Refused to load the s ...

Maintain the same javascript variable throughout multiple pages

I am working on a project that involves utilizing a database along with 2 drop down menus. Through the use of JavaScript, I am able to capture the value selected from the drop down menus and then pass it on to my PHP script. The PHP script retrieves releva ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

Trigger a Vue method using jQuery when a click event occurs

I'm attempting to attach a click event to an existing DOM element. <div class="logMe" data-log-id="{{ data.log }}"></div> ... <div id="events"></div> Struggling to access external Vue methods within my jQuery click handler. A ...

Tips for saving images in an S3 bucket

Within my express application, I currently save images to a directory in my repository. However, I am beginning to think that this approach may not be ideal and I am considering using AWS S3 as an alternative storage solution. Since I have never worked w ...