How to use image file relative to url?

Is there a way to use the relative path of the image url in a javascript file (same as css files)?

for testing, I used 2 divs and displayed a gif in the background, using css in the 1st and using js in the second:

-my file directory: root /index.html

root / module1 / test.css

root / Module1 / test.js

root / module1 / img.gif

-index.html code:

<html>
  <head>
    <link href="module1/test.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <P id="p1"> Line 1 </P>
    <P id="p2"> Line 2 </P>
    <script type="text/javascript" src="module1/test.js"></script>
  </body>
</html>

-test.css code:

#p2 {background: url('img.gif')}

in css i can use relative path.

-test.js code:

document.getElementById("p1").style.backgroundImage = 'url(./module1/img.gif)';

but in js I have to use the absolute path or it does not work.

-img.gif - you can use any gif image.

I tried to search the Internet, but I just got confused :(

Help plz :)

Ps: if you know the solution in jquery, I also appreciate it.

+2
3

CSS .

, JavaScript, .

, , , .

url("module1/img.gif");

.

.

, , javaScript, .

:

.p2_img_gif {background: url('img.gif')}

, ,

document.getElementById("p2").className = "p2_img_gif";

, jQuery addClass() removeClass().

+2

Firefox 3.6.

<!doctype html>
<style>
div { background: red; width: 80px; height: 80px }
</style>
<script>
window.onload = function() {
  document.getElementById("test").style.backgroundImage = 'url("green.png")';
}
</script>
<p>There should be no red.</p>
<div id="test"></div>

green.png - . ?

0

As an option to use the element's inline style

var element = document.getElementById("p1");
var imageUrl = './module1/img.gif';
element.setAttribute('style', 'background-image: url(' + imageUrl +');');
0
source

All Articles