Changing the Image Path According to the Device's Retina Ratio

I'm currently setting up a website for a photographer and working on creating a gallery. To streamline the process, I have automated many aspects such as file names, paths, widths, lightbox classes, etc.

All I have to do in the HTML is write an <a> tag with a title, and jQuery handles the rest.

HTML

<a alt="All-my-Loving"></a>

jQuery

$(function () {
    $('.imagesContainer a').each(function () {
        var $link = $(this),
            title = $link.attr('alt'),
            thumb = 'images/portfolio/thumbs/' + title + '.jpg';

    $link.attr('data-target', 'flare');          
    $link.attr('data-flare-scale', 'fitmax');    
    $link.attr('data-flare-thumb', thumb);       
    $link.attr('data-flare-gallery', 'main');    
    $link.addClass('item');                      
    $link.attr('href', 'images/portfolio/full/' + title + '.jpg'); 

    $link.append($('<img>', {
      src     : 'images/portfolio/thumbs/' + title + '.jpg'    
    }));
    });
});

The Challenge:
The image path leads to regular (@1x) images but to ensure compatibility with retina screens, I need it to lead to @2x or @3x images when necessary.

I've considered using Retina.js but since all image sources are determined after the script execution, this may not be feasible.

Key Requirement:
I must find a way to serve retina images without downloading both 1x and 2x versions simultaneously.

Any suggestions?


Potential Solution:
Incorporating an IF statement to determine if the device has retina graphics could help resolve the issue.

If (window.devicePixelRatio > 1) {
    $link.append($('<img>', {
      src     : 'images/portfolio/thumbsRETINA/' + title + '.jpg'
    }));
} else {
    $link.append($('<img>', {
      src     : 'images/portfolio/thumbsREGULAR/' + title + '.jpg'
    }));
}

This IF statement can be applied to each Image Path request to check if the device supports retina display.


Update
After implementing the IF statement, it appears to be functioning correctly. The Retina folders remain empty, and only devices with retina displays will load appropriate images. However, I am uncertain if this method is optimal. The modified script now looks like:

$(function () {
    $('.imagesContainer a').each(function () {
        var $link = $(this),
            title = $link.attr('alt'),
            thumb = 'images/portfolio/thumbs/' + title + '.jpg';
            retinaThumb = 'images/portfolio/thumbs-retina/' + title + '.jpg';

    // Regular tags
    $link.attr('data-target', 'flare');
    $link.attr('data-flare-scale', 'fitmax');
    $link.attr('data-flare-gallery', 'main');
    $link.addClass('item');
    $link.attr('href', 'images/portfolio/full/' + title + '.jpg');

    // Retina tags
    if (window.devicePixelRatio > 1) {                  
        $link.attr('data-flare-thumb', retinaThumb);
        $link.attr('href', 'images/portfolio/full-retina/' + title + '.jpg');
        $link.append($('<img>', {
          src     : 'images/portfolio/thumbs-retina/' + title + '.jpg'
        }));
    } else {                                            
        $link.attr('data-flare-thumb', thumb);
        $link.attr('href', 'images/portfolio/full/' + title + '.jpg');
        $link.append($('<img>', {
          src     : 'images/portfolio/thumbs/' + title + '.jpg'
        }));
    }

    });
});

Answer №1

Here's a theoretical solution for implementing retina images. This code snippet can be adjusted to fit your specific requirements.

To add a data-retina-src attribute to each image using jQuery, you can use the following code:

<img src="image.jpg" data-retina-src="image2X.jpg" alt="">

Utilize jQuery media queries to switch the image source based on the data-retina-src attribute.

UPDATE 1:

For information on detecting retina support with jQuery, refer to these resources:

Retina Detection by Egor Khmelev

Best Practices for Retina Detection in JavaScript

UPDATE 2:

You can incorporate the script provided at to automatically handle alternate images:

For example, if your HTML contains an image tag like this:

<img src="/images/my_image.png" />

The retinajs script will search for a higher resolution image on your server at this path: "

/images/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f29f8bad9b9f939597b2c08adc829c95">[email protected]</a>
"

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

Tips for iterating through a JSON object's values with jQuery AJAX

Is there a way to iterate through the json data with HTML content fetched from an ajax call in Jquery? For instance, I want to calculate the number of li tags within the provided data that have a specific class. I am looking to count the number of li tags ...

How can I implement Jquery ajax calls in various JavaScript functions?

I'm encountering an issue with a particular function in my code function readComm(){ $.post("something.php", {read:"read"}, function(data){ retVal = $.trim(data).toString(); console.log(retVal); return retVal; }); } T ...

Discover the magic of TransformToggle and slideToggle in Javascript, HTML, and CSS

Working on a website coding project and ran into an issue. Trying to utilize an img as a link to slideToggle content. It's working, but I'd like the img to rotate 90deg on the first click and -90deg on the second one. Any solutions are greatly ap ...

The issue of losing session data in Laravel 4 due to multiple AJAX requests

There is an issue on my page where photos are lazy loaded via AJAX, and sometimes all session data gets lost while the photos are loading. This problem does not occur consistently every time the page is loaded. I have already checked for session timeout or ...

The button remains in a pressed state when viewed on a mobile device

This button is functioning properly in desktop view, but in mobile view the button remains pressed down. :root { --green: #4285f4; --black: rgba(9, 13, 25, 0.752); --box-shadow: .4rem .4rem 1rem #ccc, -.4rem -.4rem 1rem #fff; --box-shadow-inset: ...

What is the process for adjusting positioning in bootstrap?

After spending countless hours attempting to create a responsive webpage using the bootstrap grid system, I have hit a dead end. Here is the code I have been working with: <div class="row"> <div class="col-md-2" align=&quo ...

Executing jQuery code after PHP content has loaded

I am currently working on a website using the Big Commerce platform. The cart page is constructed using PHP snippets, but unfortunately, I do not have access to the PHP files. My goal is to extract the value of a span tag at a specific index and use this v ...

Discover the technique for splitting a string using jQuery with multiple strings as separators

I am looking to split a string in jQuery or JavaScript using multiple separators. When we have one string as a separator, our code looks like this: var x = "Name: John Doe\nAge: 30\nBirth Date: 12/12/1981"; var pieces = x.split("\n"), p ...

Utilizing jQuery within the WordPress editor

Let's set the scene: I'm working on a WordPress admin page titled Contact Us. I've crafted a form and a submit button within the WYSIWYG editor, with the intention of using $.post to handle the form submission. Here's how it looks ins ...

The functionality of the jQuery scroll feature appears to be malfunctioning

I am trying to implement a scroll event and have written the following code: <script type="text/javascript> $(function () { $(window).scroll(function () { alert($("body").scrollTop()); }); }); ...

Using jQuery to assign the value of a hidden element to data being posted

When using jQuery's post() method to call an ajax action that returns JSON data ({"Success": "true" } or {"Success": "false"}), the value of a hidden HTML element is supposed to be set to the Success value in the returned object. However, after settin ...

Show or hide text when list item is clicked

This is the rundown of services <div> <a href="#hig"><button class="tag-btn">High blood pressure Diabetes</button></a> <a href="#hih"><button class="tag-btn">High ch ...

The mobile responsive view in Chrome DevTools is displaying incorrect dimensions

Seeking some clarification on an issue I encountered: I recently created a simple webpage and attempted to make an element full width using width: 100vw. However, I observed that on screens smaller than around 300px, the element appeared smaller and not t ...

Implement a sequence of animations within a div using jQuery

My goal is to create an animation effect for each div element within a row when the user scrolls down to that specific point on the page. The layout consists of three <div> elements in the same row. The structure of the HTML code is as shown below: ...

How can a regular number be used to create an instance of BigInteger in jsbn.js?

I attempted both methods: const num1 = new BigNumber(5); And const num2 = new BigNumber(7, 10); However, I encountered the following error: Error: 'undefined' is not an object (evaluating 'num2.nextBytes') bnpFromNumberjsbn2.js:126 ...

The relationship between elements and text input positioning

I am faced with a unique challenge. As a user types in an input field, I need to display a reset button positioned center right of the input. I must adhere to the current HTML structure for the label, input, button, and error message and I prefer not to r ...

Ways to display text when hovering over an image link

Despite trying various techniques recommended by fellow Stackoverflow users who faced similar issues, I still encountered a problem where the text appeared below the image even after applying the suggested methods to my code. I also experimented with a me ...

Developing an Easy-to-Use PDF Popup Interface

I need a simple PDF modal where I can input the text: 'The sky is blue' and have it link to a PDF that opens up when clicked. I found a similar sample online, but it includes an image plus an image modal that pops up. I want to replace the imag ...

Determine the currently active view on a mobile device

I am trying to determine whether the user is viewing the website vertically or horizontally on their mobile device or iPad in order to adjust the image scale accordingly. For example: If the user is viewing the page horizontally, I want the image style t ...

How to locate the initial paragraph element using jQuery

The scenario is as follows: $(content).filter("p:first").text(); assuming that content = <div> <div> <div> <p>adsdas</p> <p>dsa</p> <p>dsa</p> <p>dsa</p> </div> <p>&nbsp;& ...