Swap image src with PHP / HTML variable

Asked

Viewed 1,295 times

-1

If anyone can help me, I’d appreciate it. I would like to create a structure where the file path is replaced by a button that changes the image number, thus:

Variable XXX = image number (image_XXXX.jpg)

First I think I’d have to assign 0001 to the image number, that would be on the page upload, right?


XXXX = 0001;


BUTTON NEXT IMAGE

If XXXX = 1303
       Doing nothing, after all this is the last picture
Otherwise
       Add 1 to image number
       Show image


PREVIOUS NEXT BUTTON


If XXXX = 1
       Doing nothing, after all this is the first picture
Otherwise
       Remove 1 to image number
       Show image



If anyone knows how to do using PHP / JAVASCRIPT / HTML I thank.

  • If you post the code involved in the question, you have a better chance of getting someone to answer. Read this post that will help you to better elaborate your questions. https://answall.com/help/mcve

  • Stackoverflow does not distribute code, just revise or fix

1 answer

0

You can do it the way you thought, but you’d need to use php and javascript to make asynchronous requests.

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

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

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

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

With this it is now possible to make this control to exchange the image only with javascript quickly, easily and also efficiently, since you will only change the src and with it the browser itself takes care to reload 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 make the buttons and could also put a id on the image tag to use on the jQuery selector not to bug everything if you add another and so on, but I think I understand the concept.

I hope I’ve helped.
A big hug!

Edited

Also remember to update the value of data-count each click on each of the buttons.
I forgot to put this in the code, but it’s important for it to work properly...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.