Tips for optimizing images for mobile screens and ensuring responsiveness

I'm trying to ensure that my image only loads on mobile screens and remains responsive so it doesn't stretch. However, the code I've written isn't working as expected. Currently, the image takes up the whole browser window and appears on all screen sizes.

Any suggestions on how to resolve this issue? Here is a fiddle with my current code:

HTML:

<img id="yourimage" src="https://cdn.pixabay.com/photo/2016/05/02/22/16/apple-blossoms-1368187_960_720.jpg">
<p>
    Why does the image warp when resizing why doesn't it only open on 500px screens and lower?
</p>

CSS:

 #yourimage {
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    width: 50%;
    height: 50%;
}

@media (max-width: 500px) {
    #yourimage {
        display: block;
    }
}

JS:

function showPopup() {
    document.getElementById('yourimage').style.display = 'block';
}
showPopup(); // show modal image.

function closePopUp() {
    document.getElementById('yourimage').style.display = 'none';
}

document.getElementById('yourimage').addEventListener('click', closePopUp); // hide modal image

Answer №1

Simply eliminate the invocation of the showPopup() javascript function. It is also advisable to utilize

@media only screen and (max-width: 500px)
rather than just @media (max-width: 500px):

function showPopup() {
  document.getElementById('yourimage').style.display = 'block';
}

function closePopUp() {
  document.getElementById('yourimage').style.display = 'none';
}

document.getElementById('yourimage').addEventListener('click', closePopUp); // hide modal image
#yourimage {
  display: none;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  width: 50%;
  height: 50%;
}

@media only screen and (max-width: 500px) {
  #yourimage {
    display: block;
  }
}
<img id="yourimage" src="https://cdn.pixabay.com/photo/2016/05/02/22/16/apple-blossoms-1368187_960_720.jpg">

<p>
  Why does the image warp when resizing why doesn't it only open on 500px screens and lower?
</p>

Answer №2

For correct functionality, make sure to delete the showPopup() function from your JavaScript code.

Answer №3

The issue you are facing is that javascript is overriding the display: block in the css with display = 'block' which is being inserted with showPopup();

function showPopup() {
  document.getElementById('yourimage').style.display = 'block';
}
// showPopup();

function closePopUp() {
  document.getElementById('yourimage').style.display = 'none';
}

document.getElementById('yourimage').addEventListener('click', closePopUp); // hide modal image
#yourimage {
  display: none;
    position: absolute;
  top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  width: 50%;
  height: 50%;
}

@media (max-width: 500px) {
  #yourimage {
    display: block;
  }
}
HTML:
<img id="yourimage" src="https://cdn.pixabay.com/photo/2016/05/02/22/16/apple-blossoms-1368187_960_720.jpg">

<p>
Why does the image warp when resizing why doesn't it only open on 500px screens and lower?
</p>

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

What is the best way to import a file in meteor version 1.3?

Trying to incorporate react-datepicker into a meteor 1.3 and react project has been quite successful so far. The only issue I am facing is the inability to access any of the css styles from the package. According to the readme, I'm supposed to requir ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

What is the best way to validate the accuracy of an HTML form response by using PHP through $.post, all while keeping the answer confidential?

Currently, I am working on a fill-in-the-blank quiz. In my PHP file named index.php, my objective is to validate the user's input against the correct answer stored in my MySQL server. One approach I considered was to simply echo the answer using < ...

Troubleshooting: Why isn't my HTML5 video functioning

I recently added this element to my HTML file and upon previewing it in the browser, I noticed that the video box with controls appeared. However, I encountered a problem where I couldn't press play as the controls would turn from white to gray and be ...

Prevent the selection of rows and only enable the option to select checkboxes in PrimeNG's Multiselect feature

I'm currently working on a task that involves using PrimeNG multiselect. This particular multiselect includes checkboxes followed by text within each row. I need to disable the ability to select rows by clicking on the text, and instead only allow sel ...

Unsuccessful outcome from using a basic Ajax call alongside a result handler

Here is the JavaScript code: <script> jQuery(document).ready(function(){ // ensure DOM is ready jQuery('#veranstort').change(function(){ // trigger when input changes origin = "55767 Schwollen"; destination = "13509 Be ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

An unexpected issue occurred while converting XML data into JSON format

I have been using a piece of code that converts XML to JSON: // Converting XML to JSON var XmlToJson = function xmlToJson(xml) { //console.log('called xmltojson'); //console.log(xml); // Creating the return object var self = this ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Avoid special characters (metacharacters and diacritical marks)

When my program consumes data from an API, it receives the following output: "<a href=\"http:\/\/www.website2.com\/\" target=\"_blank\">Item card<\/a>","<img src=\"https:\/\/website.com ...

Obtaining rotate3d values using JavaScript / jQuery

When dealing with an element that has a transformation like the following: style="transform: rotate3d(1, 0, 0, -50deg);" I am looking to extract the value -50 using Javascript or jQuery. It's essential for me to get the absolute value, so negative d ...

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

Issue with HTML Form Data Not Being Reflected in SQL Database

After creating a form to insert values into the database, there seems to be an issue where the database is not being updated despite no errors. Here is the HTML code for the page: <!DOCTYPE html> <html> <title>css</title> <body ...

What is the process for incorporating a Bootstrap link into a specific ReactJS file?

In my current project using React JS, I found the need to incorporate Bootstrap in certain pages. To do this, I initially placed the following code snippet in the Public folder within index.html: <link rel="stylesheet" href="https://netdna.bootstrapc ...

Transformation of intricate object

I am currently in search of a reliable utility (such as Lodash) that can assist me in transforming deeply nested objects like the example shown below: Source Data: [{ "category": "blogs", "results": { "__type": "SearchProvider.SearchResultCon ...

Bringing audio to life in a dynamic AJAX chat environment

In my AJAX chat, I am utilizing the Audio class to play a sound when a new message is received. Below is my code snippet: if ( ! $.browser.msie || ( $.browser.msie && parseFloat(jQuery.browser.version) >= 9 ) ) { //var notif = new Audio(&apo ...

The process of uploading a file to the server directory via ajax is not functioning correctly. Despite attempts to upload the image, it does not successfully transfer to the designated upload

I am encountering an issue with uploading files to the server upload directory using AJAX. The image is not being successfully uploaded and I keep receiving a "connection reset" error. Can you please review my code below to see if there are any mistakes? T ...

Traverse JSON data using associative loops

Is there a way for me to iterate through this JSON data without using numerical indexes? I want to treat it like an associative array. This is what I have so far: $.post('/controlpanel/search', { type: type, string: string }, function(data){ ...

Removing the year data and converting the month in JavaScript

Currently, I am utilizing the following code snippet to parse XML in Javascript: $this(find).text() When this code runs within an HTML environment, the output for the date from the XML data appears as: 2014-04-07T19:48:00 My objective is to format it l ...

Troubleshooting: JSColor Is Failing to Function Properly in Volusion's

Recently, I've encountered some issues with the JSColor plugin () on the Volusion e-commerce platform. Despite having successfully used it before, getting it to load correctly seems to be a challenge. My current task involves working on a test produc ...