Reputation: 8477
I am using a javascript file to do some button displays .When a user clicks on a button ,the current button's image is replaced by another image (thus creating the effect that a new button appears in place of the old one) and vice versa.I created an <img>
element with an id='imgbutton' and uses the elements attr('src',newimage)
to display these buttons.
I was putting the javascript file in {{MEDIA_URL}}/js
directory sothat the file can be added to template using
<script type="text/javascript" src="{{MEDIA_URL}}/js/myscript.js" ></script>
In the javascript code(jquery 1.7.1),I am setting the image like this
..
var btnimg=$('#imgbutton');
btnimg.attr('src','{{MEDIA_URL}}/img/NewImage.png');
This causes a 404 error
in javascript console..and a placeholder is shown instead of the image.
In the django templates ,the {{MEDIA_URL}}/img/OldImage.png
is properly displayed..it is only in the javascript that the problem occurs..Can someone help me figure out why this happens?How do I correct this?
Upvotes: 0
Views: 2686
Reputation: 17713
Your problem is that the JS file is not processed by Django's template engine. When I need to do this I normally put a small bit of JS directly in the the page to set variable values, and then that is referenced by the JS file that is loaded with the <link>
tag.
Update:
Yes, you want to do something like this:
<script>
// first set the value you will be using.
var MEDIA_URL = "{{MEDIA_URL}}"; // and anything else you need to set
</script>
<script type="text/javascript" src="{{MEDIA_URL}}/js/myscript.js" ></script>
Now you can reference that global value inside the JS file, e.g.:
btnimg.attr('src',MEDIA_URL+'/img/NewImage.png');
If there are a lot of these things, an Array or Object that holds all of them keeps your namespace tidy.
Upvotes: 3