Change image src through jquery

Asked

Viewed 6,229 times

7

I’m using the plugin Animated Responsive Image Grid and I want to change the image src through Javascript/Jquery.

Html code:

<div id="ri-grid" class="ri-grid ri-grid-size-1 ri-shadow">
<ul>
    <li><a href="#"><img src="images/medium/1.jpg" alt="Whatever works"/></a></li>
    <li><a href="#"><img src="images/medium/2.jpg" alt="Anything else"/></a></li>
    <!-- ... -->
</ul>

and I have an array of image links with variable size

vectorImagens=[]

The aim is to change the src="images/medium/1.jpg" for src=vectorImagens[0], and src="images/medium/2.jpg" for src=vectorImagens[1] and etc

  • Look at this question, it’s basically the same thing. http://answall.com/questions/5754/comortrocar-o-img-src-de-uma-imagem-pequena-por-uma-imagem-grande/.

2 answers

3

It’s simple, using jQuery you can do the following:

var vectorImagens = ["images/medium/3.jpg","images/medium/4.jpg"];//exemplo
var len = vectorImagens.length; //tamanho do vectorImagens
var imagens = $('#ri-grid ul li a img'); //os elementos img
for(var i=0; i < len; i++){ //percorre o tamanho do vectorImagens
    imagens.eq(i).attr('src', vectorImagens[i]);
}

Example in Jsfiddle

  • Thank you @Paulo Roberto

3


What you need is to run a code that changes the attribute src every image.

Since you already have one vectorImagens, use like this:

$('#ri-grid img').each(function(i){
    vectorImagens[i] && this.setAttribute('src', vectorImagens[i]); 
});
// Explicação:
// Iterar todas as imagens e usar o parametro i (index) que o jQuery dá para ir 
// buscar o correspondente à array vectorImagens

In case there are fewer images on vectorImagens than elements img, you can use it like this:

var contador = 0;
$('#ri-grid img').each(function(){
    if(!vectorImagens[contador]) contador = 0;
    this.setAttribute('src', vectorImagens[contador]);
    contador ++;
});
// Explicação:
// Iterar todas as imagens e usar o parametro contador para ir 
// buscar o correspondente à array vectorImagens. 
// No caso de não existir tal imagem, o if() dá true e faz reset ao contador.
// Assim a iteração de imagens continua mas a imagem buscada volta ao inicio 
// da array de imagens (vectorImagens)

Example

Option only with vanilla JS:

var contador = 0;
var imagens = document.getElementById("ri-grid").getElementsByTagName("img");
for (var i = 0; i < imagens.length; i++) {
    if (!vectorImagens[contador]) contador = 0;
    imagens[i].setAttribute('src', vectorImagens[contador]);
    contador++;
};

Example

  • 1

    Thanks @Sergio your solution was very helpful!

Browser other questions tagged

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