I would like your kind help to point the correct path of images from JS. I'm trying to change a DIV background using CSS and JS. Quite simple, right? Well, not for me in Drupal 8.

My div loads the background defined in the CSS (my_module.libraries.yml) The JS also works for changing positions of the layers (or DIVs, sorry, I'm from the Netscape times, old school). But it doesn't work for setting the background because cannot find the images. That means that there is no problems regarding routing neither configuration of the module.

So, the question is: How can I set the path for the CSS images in the JS libraries?

Here goes some codes:


  version: 1.x
      css/box-simulador.css: {}
    js/box-simulador.js: {}

Excert from the CSS file

#SimHolder {
    background: url(img/pillow.png) left top no-repeat; /* << WORKS FINE! */

Excert from the JS file

function setTowel() {
 document.getElementById('SimHolder').style.backgroundImage='url(img/towel.png)'; // DOESNT WORK :(
 document.getElementById('textHolder').style.top='30%'; // IT WORKS! 

I'm sure the answer would be quite simple ;) Thanks in advance!

  • It depends on where you define that css libraries file. If it is a module you place that img folder in your module and define url as (../img/pillow.png). If its theme folder then in your mytheme url(../img/pillow.png). Note the two dots that for traversing back from css folder to the img folder residing in same directory. – sarathkm Mar 16 '17 at 6:13
  • The CSS is on MyModule/css and the images images are both in MyModule/img and MyModule/css/img. The console log fro mthe browser says it is looking for ww.damon.com/img/image.png ... its trying to reach the root ..... How Coul I specify the correct path? – Luis Cáceres Mar 16 '17 at 20:44

Weel, I found s solution, quite simple: just use {{directory}} on the template. ;)

  • Can you elaborate on how you used {{directory}} on the template? Did you load your javascript file on the twig template? – mlanning Aug 28 '17 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.