Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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....

like image 965
Ian Dimmick Avatar asked Sep 28 '13 11:09

Ian Dimmick


People also ask

How to insert background image using JavaScript?

backgroundImage = "url('image. png')"; You need to put the relative path to the image from your web page's folder. If the image is located in the same folder, then you can reference it directly inside the url() function as in the code above.

How do I add a background image to my URL?

Usage is simple — you insert the path to the image you want to include in your page inside the brackets of url() , for example: background-image: url('images/my-image. png'); Note about formatting: The quotes around the URL can be either single or double quotes, and they are optional.


2 Answers

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+')';
like image 128
adeneo Avatar answered Nov 15 '22 07:11

adeneo


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 + ')');
like image 27
Nicolás Straub Avatar answered Nov 15 '22 05:11

Nicolás Straub