Ian Dimmick
Ian Dimmick

Reputation: 73

Insert javascript variable as background image source

I have a variable that I can display on the page by using the following <script>document.write(image)</script>

I can copy the result to the browser and it displays the file I require.

What I want to do is to take that variable and use it to specify the src of my background image

`<p style="background-image: url(**image**);">`

I know that this is probably simple to you guys, but I have spent the whole day and am losing a lot of hair over this one. Thanks for your time....

Upvotes: 7

Views: 23840

Answers (3)

Ian Dimmick
Ian Dimmick

Reputation: 73

I didn't give enough background in my original question...

ie; I forgot to mention that I was attempting to do this in the middle of a server side loop.

I achived what I had set out to do with the following code

`<script type="text/javascript">document.write("<table background=\"http://..../Pages/"+image+"/bkg.jpg\" >");`

Thank you VERY much for your help !!

Upvotes: 0

Nicolas Straub
Nicolas Straub

Reputation: 3411

Give the <p> element an id:

<p id="myPElement">

Manipulate it in the dom...

document.getElementById('myPElement').style.backgroundImage = 'url(' + image + ')';

... or with jquery:

$('#myPElement').css('background-image', 'url(' + image + ')');

Upvotes: 8

adeneo
adeneo

Reputation: 318342

If the element is selectable :

<p id="paragraph">Some text</p>

You can change the style with javascript:

document.getElementById('paragraph').style.background = 'url('+image+')';

if you're creating the paragraph you can do:

var p = document.createElement('p');
p.style.background = 'url('+image+')';

Upvotes: 9

Related Questions