Swap the image source with a different image attribute when making the website responsive

I have implemented a custom attribute for the img tag in my code, such as data-tablet and data-mobil

<div class="myDiv">
 <img  src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg">
</div>

My goal is to have the image source change dynamically depending on the screen size, so if the screen is a tablet, the src should change to data-tablet, and if it's a mobile screen, the src should change to data-mobil

Here is my JavaScript code:

$(document).ready(function(){

    $(window).resize(function(){
      var tabletSrc = $(".main-carousel img").attr("data-tablet");
      var mobilSrc = $(".main-carousel img").attr("data-mobil");
      if($(window).width() <=768){

         $('img').attr('src',tabletSrc);
      }
      if($(window).width() <=480 ) {
         $('img').attr('src',mobilSrc);
      }
  });

});

Click here to view my code on Codepen

The question I have is how can I achieve this behavior without any functionality when clicked.

Note: I prefer not to use srcset or CSS for this purpose.

Answer №1

To see a functional version, please visit this CodePen link.

Upon reviewing your code, the following issues were identified:

  • The code meant for both mobile and tablet cases was being executed in the mobile scenario only.
  • The selector $(".main-carousel img") targets a group of images, not a single one. To address this, consider utilizing .each() to operate on individual images.

Below shows the relevant portion of the code:

$(window).resize(function() {
  if ($(window).width() <= 480) {
    $('img').each(function() {
      $(this).attr('src', $(this).attr('data-mobil'));
    });
  } else if ($(window).width() <= 768) {
    $('img').each(function() {
      $(this).attr('src', $(this).attr('data-tablet'));
    });
  }
});

Answer №2

Opt for using srcset over JavaScript-based validations for different device dimensions.

<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 200w, images/space-needle-2x.jpg 400w,
images/space-needle-hd.jpg 600w"> 

By doing this, the browser can automatically select and display the appropriate image based on its dimensions.

For more information, visit

https://www.sitepoint.com/how-to-build-responsive-images-with-srcset/

Answer №3

If you're looking to create a carousel with multiple images, give this a try

function resizeImages(){
  var imgSource = $(".myDiv img");
  if($(window).width() <=768 && $(window).width()>480){
    $(imgSource).each(function(key,value){
      $(value).attr('src',$(value).data('tablet'));
    });
  }else if($(window).width() <=480 ) {
    $(imgSource).each(function(key,value){
      $(value).attr('src',$(value).data('mobile'));
    });
  }else{
    $(imgSource).each(function(key,value){
      $(value).attr('src',$(value).data('default'));
    });
  }
}

$(document).ready(function(){
    $(window).resize(function(){
        resizeImages();
    });
    resizeImages();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="myDiv">
 <img  src="org1.jpg" data-default="org1.jpg" data-tablet="tablet1.png" data-mobile="mobile1.jpg">
 <img  src="org2.jpg" data-default="org2.jpg" data-tablet="tablet2.png" data-mobile="mobile2.jpg">
 <img  src="org3.jpg" data-default="org3.jpg" data-tablet="tablet3.png" data-mobile="mobile3.jpg">
</div>

Note Make sure to provide correct image sources before testing. The code above is designed for use with multiple images.

Answer №4

It seems like you may be using the incorrect class name in your code. Your div is assigned the class "myDiv" but you are trying to select it using the class name "main-carousel"

$(document).ready(function(){

    $(window).resize(function(){
      var tabletSrc = $(".myDiv img").attr("data-tablet");
      var mobilSrc = $(".myDiv img").attr("data-mobil");
      if($(window).width() <=768){

         $('img').attr('src',tabletSrc);
      }
      if($(window).width() <=480 ) {
         $('img').attr('src',mobilSrc);
      }
  });

});

You can find the codepen link here

Answer №5

Always prioritize the validation for tablet when dealing with different screen sizes, as 480 < 768

Make sure to adjust your conditions accordingly:

$(window).resize(function(){
      var tabletImage = $(".someDiv img").attr("data-tablet");
      var mobileImage = $(".someDiv img").attr("data-mobile");
      var defaultImage = "defaultImagePath"; //default image source
      var screenWidth = $(window).width();
      if(screenWidth <= 480 ) { //for smaller screens
         defaultImage = mobileImage;
      }else if(screenWidth <= 768){ //for larger screens
         defaultImage = tabletImage;
      } //default image will be used if none of the conditions are met.
});

Answer №6

Consider implementing this solution:

$(window).resize(function(){

var actualImage =  $(".carousel-main img").attr();
var tabletSource = $(".carousel-main img").data("tablet"); //prefer using .data over attr
var mobileSource = $(".main-carousel img").data("mobile");

  if($(this).width() <= 768){
     $('img').attr('src',tabletSource);
  }
  else if($(this).width() <= 480 ) { //use else if instead of if
     $('img').attr('src',mobileSource);
  }

  else{
   $('img').attr('src',actualImage);
  }

});

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

The custom CSS file is not being recognized

I am facing an issue while trying to integrate two CSS files into my website. The second CSS file seems to be ignored, even though both files are properly loaded when inspecting with the Development Tool in Chrome. Here is a snippet from my Header: <l ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

The issue with Ionic 2 arises when attempting to use this.nav.push() because it

Recently transitioning from Ionic 1 to Ionic 2, I'm encountering an issue with using this.nav.push(nameOftheOtherPage) immediately after a promise. Interestingly, the function this.nav.push works fine when it's called outside of the promise funct ...

Getting the nth-child rule for CSS in IE9 to function properly in IE8

This code is functioning in IE9: body.country-XYZ .abc:nth-child(3) { display:none; } As :nth-child() is effective in IE9 and newer versions, what can be done to ensure it also functions on IE8? Can you suggest an alternative method for achieving th ...

Search MongoDB to find, update, and validate any empty fields in the body

I'm currently working on updating a user's profile information, but I'm facing a problem with checking for empty values before proceeding with the update. The code I've written so far is not displaying error messages and is preventing m ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

Guide on adding dual horizontal scroll bars to a v-data-table (Vue / vuetify)

Currently, I am working on Vue / Vuetify and experimenting with the v-data-table component. While creating a table, I noticed that it has a horizontal scroll bar at the bottom. https://i.stack.imgur.com/noOzN.png My goal now is to implement two horizontal ...

Importing JSON Data into an HTML File

I need to load a JSON file containing HTML content into my main HTML file upon clicking a button. ABC.json includes: <li><img src="images/picture6.jpg" /></li> <li><img src="images/picture5.jpg" /></li> <li><i ...

The fixed div with the z-index at the top isn't functioning properly

I need a div that remains fixed at the top of my page and overlaps any other elements on the page, similar to the blue search bar on Facebook. Currently, when I scroll down, the table ends up above the div, but I want it to be below the div instead. Here i ...

Can you customize the buttons in the operation panel of an antd image preview window?

https://i.sstatic.net/hZLOn.png I am looking to add a button that allows users to download or share the image being previewed. Is there a way to achieve this functionality? I have researched and read through the documentation but have not found a solutio ...

The line directly following the first line within the <li> element is located in the same position

I need help with customizing the bullet background-image for an <li> element. I want the text in the bullet to be displayed outside the marker using the CSS property list-item-position: outside. However, my current implementation doesn't seem to ...

Is it possible for me to create a Pomodoro clock similar to this one?

Can you provide guidance on creating a Pomodoro clock similar to this design: https://i.sstatic.net/qhd1Z.png As time progresses, the arrow should move around causing the circumference of the circle to increase. What approach or library would you recomm ...

What is the most efficient way to find the parent element with the fewest children?

In close proximity are two containers, each containing a series of smaller containers. <ul class="containers"> <li>Matt</li> <li>John</li> <li>Mark</li> </ul> <ul class="containers"> &l ...

How to vertically align content using Zurb Foundation's equalizer feature?

I am currently utilizing Zurb Foundation 5 along with the equalizer component. In a scenario where I have three columns of equal width, I am aiming to achieve vertical center alignment for the content (text) in the middle column and vertical bottom alignme ...

Is it possible to utilize the WebGL camera in order to create dynamic transitions between various polygons?

Recently, a friend suggested exploring WebGL as an alternative to CSS transitions. I have a collection of polygons that form a 2D board game. https://i.sstatic.net/D0dnc.png In essence, the application moves the player space by space starting at the top ...

What are the steps to modify the placeholder of the formik <Field/> component?

Struggling to figure out how to make the date input empty with Formik. I just want it to display nothing initially, but have been unable to do so after hours of trying different methods. <Field name="date" type="date" className ...

Using AJAX to dynamically load content in HTML

I've been working with this AJAX function: type: "GET", url: url, cache: false, dataType: 'html', success: function(data){ }, error: function(){ }, ...

Creating a fixed sidebar that remains visible while scrolling in Next.js

Currently, I am faced with the challenge of implementing two components - a feed and a sidebar. The sidebar contains more content than it can display at once, so I want it to be able to overflow. My goal is to have the sidebar scroll along with the content ...

Angular 2 keypress validation: Ensuring data integrity through real-time input verification

I am currently facing an issue with implementing number validation in my Angular2 project. I am struggling to replicate the JavaScript code provided below. Here is the HTML: <input type="text" class="textfield" value="" id="extra7" name="extra7" onkeyp ...

The use of special characters in jQuery for specific selectors

I'm currently attempting to implement a basic hover effect on a special character as a selector. The special symbol I am utilizing is the double-daggers ( ‡ &#8225;) character with ASCII code 8225, and I would like it to function as a toolt ...