how to get correct site url when using javascript

jeongweejeongwee Vanilla version 2.6 ✭✭

how to get correct url when using javascript? like you can get the url by using {link path="/"} on default.master.tpl.

I want to change the background by using javascript.

The background-image changed when the page is load, but after i go to another page , the background-image disappeared.

I use this path to set the background-image, but it won't work after i go to another page.

document.getElementById("Body").style.backgroundImage="url(themes/Elegant/design/images/nontransparent/1.png)";

I check the url from chrome ,

after loading the url is http://localhost/vanilla/themes/Elegant/design/images/nontransparent/1.png and its working.

when i go to a discussion the url become http://localhost/vanilla/discussion/1/themes/Elegant/design/images/nontransparent/1.png and its not working now.

so the background-image been broken after you go to another page.

anyone has knows how to fix it on this case?

any help would be greatly appreciated.

Comments

  • jeongweejeongwee Vanilla version 2.6 ✭✭
    edited July 2018

    oh, my bad javascript has its way to get it by use document.location.origin.

  • ShadowdareShadowdare Moderator
    edited July 2018

    You can retrieve the root-relative path of Vanilla with gdn.url('/');. This will work even if Vanilla is in a sub-directory.

    For your image, you can do:

    document.getElementById("Body").style.backgroundImage = "url(" + gdn.url('/themes/Elegant/design/images/nontransparent/1.png') + ")";
    

    "gdn" is a global library that is provided on the page by Vanilla's global.js.

    Add Pages to Vanilla with the Basic Pages app

    jeongweeBleistivt
  • jeongweejeongwee Vanilla version 2.6 ✭✭

    @Shadowdare said:
    You can retrieve the root-relative path of Vanilla with gdn.url('/');. This will work even if Vanilla is in a sub-directory.

    For your image, you can do:

    document.getElementById("Body").style.backgroundImage = "url(" + gdn.url('/themes/Elegant/design/images/nontransparent/1.png') + ")";
    

    "gdn" is a global library that is provided on the page by Vanilla's global.js.

    ty man that is usefull.

Sign In or Register to comment.