1

I have a javascript function named "background_url" that outputs a random background image.

I'm trying to call the function in this way:

 <td style="<script type="text/javascript">background_url();</script>"></td>

but the only thing outputted in my browser is:

a string "background_url();"

The javascript function is as follows

function background_url(){

var myimages=new Array()
myimages[1]="images/img1.jpg"
myimages[2]="images/img2.jpg"
myimages[3]="images/img3.jpg"   
//call a random function that returns id of image etc               
     document.write('background-image: url('+myimages[id]+')');
}
       </script>

The background image is not shown,what can i do in order to fix that?

Thanks, in advance

2
  • Side comment: you should read about array literals. Commented Mar 12, 2012 at 18:44
  • Use jquery css Commented Mar 12, 2012 at 18:44

2 Answers 2

5

Don't.

Do it the right way.

Give the td element a class (if there are more than one that share the background) or an id (if this element is unique) and use JavaScript to set the style using the appropriate selector.

var tds = document.querySelectorAll('td.some-class-name');
for(var i = 0; i < tds.length; i++){
    var td = tds[i];
    td.style.backgroundImage = 'url(' + randomImageUrl + ')';
}

Or, if you're using a library like jQuery, it's a little easier:

$('td.some-class-name').css('background-image','url(' + randomImageUrl + ')');
Sign up to request clarification or add additional context in comments.

Comments

1

The thing you're running into is that script execution can happen in 2 places: inside a <script> tag (which can't be in an attribute or, as part of an attribute only if it's an event handler. So your choices are:

<script>
background_url()
</script>

Or

<script src="path/to/your/script.js"></script>

Or

<td onmouseover="background_url()">

Given those are your choices, typically people try to use the second option, meaning you'll need to have some mechanism to link your element to the code in question. So you might add an id in your td:

<td id="randomBgElement">

Then onload do this:

document.getElementById('randomBgElement').style = background_url()

Where "background_url()" is a function that returns a valid style, like background-image: url(images/img3.jpg) generated randomly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.