Skip to content
Advertisement

Change image with and js

I have a small slider that switches the preview image to the main image. It works fine now

blade.php

JavaScript

js

JavaScript

But I still have a picture mobile_image, and I want the mobile_image to change instead of main_image at the maximum size of 576px, for this I use <picture>

I change my code to like this

JavaScript

But my slider just stops working

The main image eventually changes to mobile, but the slider itself does not switch

In this case, the preview images also echo, but the main image itself does not change

My slider essentially works like this

https://jsfiddle.net/a9yvdu75/

I just need to put what in the main-image class in <picture> and change the image depending on the screen size

Advertisement

Answer

This line is problematic:

JavaScript

The symbol > means that img must be an immediate child of .main-image. So you have to choose one of the selectors $('.main-image img') or $('.main-image > picture > img'). But that still won’t work because…

The second problem is that you don’t fully understand how <picture> works. The browser chooses <source> to display itself, based on the rules in media. And the same <img> is only for browsers, which doesn’t support <picture>. So setting .attr('src' only works if you remove all <source>.

Also in many places you use .children('img').

So if you want to do such substitutions, you have to remove responsive image selection.

I believe the quickest solution for you is to use an alternative syntax. (You will still need to programmatically remove srcset, sizes)

JavaScript

Another alternative is to swap the entire .main-image section. eg.:

JavaScript

And using JS like:

JavaScript

You must store “desktop” and mobile sources in the thumbnail.

JavaScript

The rest is just tedious gluing of strings.

//EDIT: one of possible solutions.

JavaScript

Remember, in JS you work with already generated HTML (provided data), you do not have access to PHP variables.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement