Reputation: 2325
I am successfully creating a Cloudinary image as follows:
{% cloudinary photo.filename
width='300'
crop='fill'
class='item_photo'
id=photo.filename %}
Which results in html img tag:
<img
class="item_photo"
id="xxxxxx"
width="300"
src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg">
However, I want to add an onClick
event to the img, but am not able to figure out the correct syntax or perhaps even if it is possible.
I would like html tag to look like:
<img
class="item_photo"
id="xxxxxx"
width="300"
onClick=imageClick('xxxxxx') <=== event variable is same as `id` value
src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg">
The id
and imageClick
variable are themselves populated by Django template tag value photo.filename
.
Some things I've tried:
onClick='photoClick(photo.filename)' %}
{% with add:'onClick=photoClick('{{ photo.filename }}|add:') as onclick %}{{ onclick }}{% endwith %}
|add:'onClick=photoClick('{{ photo.filename }}|add:')' %}
How can I construct the onClick=photoClick(xxx)
part of this template tag?
Upvotes: 2
Views: 297
Reputation: 164
You can add the onClick attribute to the img tag as shown below (e.g. photo.filename=sample_image):
{% cloudinary photo.filename width="300" crop="fill" class="item_photo" id=photo.filename onclick="photoClick(this)" %}
Add the script function photoClick(), which can accept the img tag object that can be processed as:
<script type="text/javascript">
function photoClick(img) {
console.log("The src data is: " + img.src);
console.log("The id data is: " + img.id);
var filename = img.src.substring(img.src.lastIndexOf('/')+1);
console.log("The filename is: " + filename);
// Other actions
var src = img.src;
window.open(src);
}
</script>
The resulting HTML tag will be:
<img class="item_photo" id="sample_image" onclick="photoClick(this)" src="https://<your_cloudinary_image_url_path>/sample_image.<ext>" width="300"/>
Upvotes: 3