Archived topic
Show different image on desktop and mobile
6 replies · Started by Rostyslav on July 24, 2022
Hello!
I am using the technique of block image as background image that David provided to me on this post: https://generatepress.com/forums/topic/use-new-image-block-as-background-image/
Now, I would like to display a different image on mobile.
How can I do it?
Thanks!
I used this structure: https://ibb.co/5kX2Y9q
Both images with same CSS class, but to image1 I added hide-on-mobile and for image2 I added hide-on-desktop.
The problem is that the browser is loading both images always: https://ibb.co/v4cv4ry
How can I avoid loading both images?
Thanks!
Hi there,
The problem is that the browser is loading both images always
Do you mean both images show in HTML? If so, it's normal.
CSS is not PHP, it can't change HTML.
But when the browser read the CSS in the site head, it will know that there's no need to load one of them depending on the devices' screen size.
I was also reading this topic: https://generatepress.com/forums/topic/image-in-different-locations-for-mobile-vs-desktop/.
What do you think about this technique? Does it worth?
Hi Rostyslav,
Yes, that would work if you don’t want to just hide the image block.
You would simply need two block elements and set the display rules depending on wp_is_mobile().
So in your case, something like this:
add_filter( 'generate_block_element_display', function( $display, $element_id ) {
if ( wp_is_mobile() ) {
if ( 123 === $element_id ) {
$display = false;
}
} else {
if ( 456 === $element_id ) {
$display = false;
}
}
return $display;
}, 10, 2 );
Kindly replace 123 and 456 with you Elements’ IDs.
Hello!
How can I know the id of each block elements?
Thanks!
If you edit the element, you can see the Element Id in the URL.
Example: https://share.getcloudapp.com/llu0AbZ7
Hope this clarifies!