Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background image in external stylesheet with javascript?

Tags:

javascript

I want to change the background image from external stylesheet.

For example in external stylesheet background image was:

#nav
  {
   background-image:url(../images/nav.png);
  }

Now i want to change it through javascript on run time like:

#nav
  {
   background-image:url(../images/newImg.png);
  }

I can successfully change this image by using this javascript code:

 eval('theRule.style.backgroundImage="../images/newImg.png"');

But issue is: Result looks like that:

#nav
  {
   background-image:url(http//localhost/project/images/newImg.png);
  }

I dont need http//localhost/project/ etc...

I just need ../images/newImg.png

I tried hard to fix this but i did not found any solution yet.

So Please guide me that how to resolve this issue?

Thanks for Reading my Question

Regards

like image 515
Ayyaz Zafar Avatar asked Mar 23 '26 21:03

Ayyaz Zafar


1 Answers

Try.

rule.style.setProperty("background-image", "../images/newImg.png", "");
rule.style.cssText = rule.style.cssText.replace("../images/nav.png", "../images/newImg.png"); //Replace all images

But if not helped, then do not find easy ways.

like image 175
user1835582 Avatar answered Mar 26 '26 11:03

user1835582



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!