How to replace the src of an img tag?

7

I have an html page that shows an image for each day of the year.

Images are organized into folders such as /img/o1/o1.jpg (referring to January 1st), and so on.

My html is simple I want you to take the day + month today and replace it in the source of an img tag

How could I do this? Javascript?

    
asked by anonymous 28.03.2014 / 03:58

4 answers

10

Do with javascript, put an id or class to identify, rescue with javascript, and change the property

var img = document.getElementById('teste');
img.src = 'teste';

sorry ... To get the date ...

var d = new Date();
var mes = d.getMonth()+1;
var dia = d.getDate();

/// alterando o src
var newImg = '0'+mes+'/'+dia+'.jpg';
img.src = newImg;

Do you understand?

    
28.03.2014 / 04:09
2

You can change the src property by using an identifier or something you can select in the image. Then you can retrieve its node with javascript and edit any attribute.

Example:

var

    // Armazena o nó da imagem.
    image = document.getElementById('id-da-imagem'),

    // Recupera um objeto com o momento atual.
    date = new Date(),

    // Recupera o mês do objeto "date".
    month = date.getMonth(),

    // Recupera o dia do objeto "date".
    day = date.getDate();

// Altera o source da imagem armazenada.
image.src = '/img/' + month + '/' + day + '.jpg';

If you want to change the attribute with jQuery:

var

    // Recupera um objeto com o momento atual.
    date = new Date(),

    // Recupera o mês do objeto "date".
    month = date.getMonth(),

    // Recupera o dia do objeto "date".
    day = date.getDate();

// Altera o source da imagem armazenada.
$('#id-da-imagem').attr('src', '/img/' + (month < 10 ? '0' + month : month) + '/' + (day < 10 ? '0' + day : day) + '.jpg');

See this jsFiddle application example: link

    
04.04.2014 / 13:59
2

You can insert the images on your page into hiddens fields and do the validation they displayed above in JS:

var

    // Armazena o nó da imagem.
    image = document.getElementById('id-da-imagem'),

    // Recupera um objeto com o momento atual.
    date = new Date(),

    // Recupera o mês do objeto "date".
    month = date.getMonth(),

    // Recupera o dia do objeto "date".
    day = date.getDate();

// Altera o source da imagem armazenada.
image.src = '/img/' + month + '/' + day + '.jpg';

That from there will work perfectly!

    
04.04.2014 / 14:48
0

Javascript, put a command to CAPTURE DATE , make a selector by capturing the img element and change the src attribute by assigning the date in the desired format (/img/o1/o1.jpg)

    
28.03.2014 / 04:12