0

I have some jquery code that toggles an active vs. inactive image for a button when a user clicks it. It works fine when I just run everything from windows statically with relative paths.

However, once I migrated it to my django dev box clicking the button will fail to load the desired image if I set a relative path to it through jquery. All other static images are serving fine through css with relative paths, but if I set the relative path through jquery on document load, for instance, it doesn't work. I've confirmed through inspect element that the paths are the same and jquery is setting them correctly.

After trying various relative paths for 20 minutes, I found out that setting the absolute path of the development server works, i.e. "url('http://127.0.0.1:8000/static/img/img.jpg'). I'd like to get relative paths working as this method has its limitations with flexibility and deployment.

Am I running into a limitation of django static file serving? Did I find a bug? Or is there something I'm missing?

Thanks in advance!

Newmu
  • 1,930
  • 1
  • 20
  • 25
  • When Googling `django relative path` I see various methods to get the path. Have you tried them, and how exactly do they not work? Where in your JavaScript are you setting the path how? – Pekka Aug 17 '12 at 08:35
  • As the CSS/JS are not rendered through templates (but linked into the html template through {{% static "relative path to css or js" %}}, I can't use those, but there would be no need to as the js/css just sit in their directories and you can use relative paths. The js is in the static directory. It's subfolders are img, js, font, css. I can set a relative path from the css like url('../img/img.jpg'), but the same thing within the js (which is on the same directory level) does not work. Relevant code would be: $('#mybutton').css('background,"url('../img/img.jpg')"); – Newmu Aug 17 '12 at 08:46

1 Answers1

2

I don't know Django, but one approach when your server-side framework gives you a root path is to export that into JavaScript in the main document:

<script>
 templateRootPath = {{% static "path to your template dir" %}}
</script>

and to then use where appropriate:

$('#mybutton').css('background,"url('"+templateRootPath+"/img/img.jpg')");
Pekka
  • 442,112
  • 142
  • 972
  • 1,088