How to replace src of an img tag?

Asked

Viewed 16,195 times

7

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

Images are organized in folders for example /img/o1/o1.jpg (for January 1) and so on.

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

How could I do that ? Javascript?

3 answers

10


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

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

sorry... for you 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;

Got it ?

  • And the date goes where? Would be able to show an example?

  • 4

    Careful, javacript always takes the local value of the machine so if it is wrong the machine you will end up bringing wrong image.

  • 3

    Or if your computer is in a different time zone than the server (which may be a bug or a Feature, depending on your intention).

  • @karmex this proposed script will affect the image with id='test' in html.

2

You can change the property src using an identifier or something you can select from the image. Then you can retrieve the node from it 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 exchange 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 application example in jsFiddle: http://jsfiddle.net/n28gk/1/

2

You can insert the images on your page into hiddens fields and do the above validation 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 will work well from there!

Browser other questions tagged

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