Home › Forums › Add-ons › Repeater Field › 2 options for responsive images in repeat field › Reply To: 2 options for responsive images in repeat field
Hello @cuartostudio
Ideally, you should use srcset
for this (explained here). But if this isn’t an option, you can also use a bit of Javascript for this:
Your HTML could look something like this:
<img src="<?php echo get_field('image'); ?>" data-small-src="<?php echo get_field('image_small'); ?>" />
Then the Javascript (jQuery):
var windowWidth = $(window).width();
if (windowWidth <= 768) {
$('img[data-small-src]').each(function() {
var small_src = $(this).data('small-src');
$(this).attr('src', small_src);
});
}
What that basically says, is if the window width is less than 768 (or whatever width you want this to happen), then find all the <img>
tags with the data-small-src
data attribute, loop through them and update its src
value, with the ‘small-src’ value which will be the URL of the smaller image.
You could optionally put that function into a $(window).resize
event too so that it swaps out the images based on image size, but then you’ll need to add an else
to that if
statement so that it reverts back to the large size if necessary.
Hope that helps?
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.