bjornio bjornio - 2 months ago 7
Javascript Question

I can change background images, but how to print link?

I am using JavaScript to randomly change the background image upon refresh. What I have been wanting to do is then take the current

background-image
url and paste it in a certain div within

<a href=""></a>


so that people can download the image.

The background image script works and is as follows:

var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}


Sorry if this is easy but I haven't been able to figure out how to do it! Can anyone point me in the right direction?

Answer

Let's assume you have this link somewhere in your document and you want it to point to the current background image:

<a href='#' id='bgDownload'>Download background image</a>

The following function changes now the "href"-attribute of the link to the current background and the background itself:

var totalCount = 3;
function ChangeIt() 
{
    var num = Math.ceil( Math.random() * totalCount );
    document.body.background = 'bgimages/'+num+'.jpg';
    document.body.style.backgroundRepeat = "repeat";// Background repeat

    // change link
    document.getElementById("bgDownload").href = 'bgimages/'+num+'.jpg';
}

I hope it helps...