Change image src with PHP / HTML variable

0

If anyone can help me, I would be grateful. I would like to create a structure where the file path is changed by a button that changes the image number, like this:

Variable XXX = image number (image_XXXX.jpg)

First I thought I would have to assign 0001 to the image number, that would be in loading the page, right?

XXXX = 0001;

NEXT IMAGE BUTTON
If XXXX = 1303
Do nothing, after all this is the last image
Senão
Adds 1 to the image number
Show image

PREVIOUS NEXT BUTTON

If XXXX = 1
Do nothing, after all this is the first image of Senão
Remove 1 from the image number
Display image



If anyone knows how to do it using PHP / JAVASCRIPT / HTML, I appreciate it.

    
asked by anonymous 14.04.2018 / 14:40

1 answer

0

You can do it this way you thought, but you would need to use php and javascript to do asynchronous requests.

A simpler way I see to do this is to use only javascript. Initially you need something like:

<img src="/caminho/para/imagem-1.jpg" />

And from this you have several ways to change the final number. One would be to get the value of the src attribute and do split to get the value, for example. But it would also be a lot of work. If it were me doing it I would use a data attribute to control that number. So just a little change in your image and look like this:

<img data-count="1" src="/caminho/para/imagem-1.jpg" />

With this you can now make this control of changing the image only with javascript in a fast, easy and efficient way, since you will only change the src and with this the browser itself is responsible for reloading the image .

In general it would look like this:

<img data-count="1" src="/caminho/para/imagem-1.jpg" />

<script>
  $('#botaoProximo').onclick(function(){
    var proxima = parseInt( $("img").attr("data-count") ) + 1;
    $("img").attr("src", "/caminho/para/imagem-"+ proxima +".jpg");
  });

  $('#botaoVoltar').onclick(function(){
    var anterior = parseInt( $("img").attr("data-count") ) - 1;
    $("img").attr("src", "/caminho/para/imagem-"+ anterior +".jpg");
  });
</script>

Of course you still have to do the buttons and could also put a id in the image tag to use in the jQuery selector so you do not bug everything if you add another one and so on, but I think you understood the concept.

I hope I have helped. A big hug!

Edited

Also remember to update the value of data-count with each click on each button.
I forgot to put this in code, but it's important for it to work correctly ...

    
16.04.2018 / 17:44