I have a set of images stored in an array and I display them by looping through the array with a "foreach".
PHP code of how I extract the images and show them:
$imagenes = $cabana->getImagenes();
//Recorremos el foreach del array "$imagenes".
$first = true;
foreach($imagenes as $imagen){
if($first){
echo "<img id='grande' src='imagenes/".$imagen."' width='260' height='260'/> ";
$first = false;
}else{
echo "<img class='peque' src='imagenes/".$imagen."' width='140' height='140'/ onclick='cambiarImagen(this)'> ";
}
}
As we can see, there is a superior image in terms of size of the rest.
The problem is the following : How do I (from the client side, javascript for example) click on one of the smaller images to replace it with the larger main image? Since the images are in an array, how do I know which image to click on? Because I only have one onClick event for all of them.
The idea would be something like this illustration:
You could assign each small image a function (using the attribute
onclick
) to which you will pass the keywordthis
. The reserved wordthis
allows you to refer to the element with which you are interacting.This way, once you get the path of the image you just clicked on, you can assign it to the big image.
Example:
Applied to your case, you would simply have to add the function in your Javascript and add the attribute
onclick
to each of the images when you print them using the statementecho
.First you should change your
PHP
, so that it is more or less like thisNotice that I have only added an ID field, to the large image, so that I can then reference
jquery
that image by.For
JavaScript
, more specifically withjquery
, the following would be doneThe only thing this does
jquery
is read the clicked image, loading it into the clicked variable and then modifyingscr
the big one with theattr
methodjquery