1

Maybe this is a really dumb question, but I'm learning Javascript and Django and can't figure it out. I've spent a few hours on this and maybe it's a syntax error or something else.

I want to specify the source of an image in javascript and then display the image in Django HTML template. It's not working, even with simple images

Here is my javascript:

$(document).ready(function() {
        var image = document.getElementById("image").src('https://res.cloudinary.com/.../{{ object.id}}');
        }

Here is my image info:

<img src="#" id="image" class="mx-auto" width="250px" onerror='this.onerror = null; this.src="https://res.cloudinary.com/.../image.jpg"'/>

What am I doing wrong? It's definitely not working - the image is not showing up even when it exists. I either get the default image or no image.

The javascript is in the HTML file and this is what I have at the top of my file:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
4
  • Is the javascript in the html file or its own file? When you view source, does the javascript link (with object_id) look right and you can click on it and it brings you to the image you want? Commented Jun 30, 2021 at 5:16
  • It's in the HTML file. This code doesn't even work with no object_id and an image link that's fully specified. Nothing comes up to click on if there is no default image specified in the HTML. If I specify a default image i.e. the one error that will show up. Commented Jun 30, 2021 at 5:17
  • I think just an issue with your js in the way you set the image url, see my answer Commented Jun 30, 2021 at 5:23
  • Try : var image =$("#image").attr('src','https://res.cloudinary.com/.../{{ object.id}}'); Commented Jun 30, 2021 at 12:53

1 Answer 1

2

Try changing your js:


document.getElementById('image').src = 'https://res.cloudinary.com/.../{{ object.id}}';

Sign up to request clarification or add additional context in comments.

5 Comments

I tried this. The broken image picture comes up.
And if you manually just put a url like this in there? https://via.placeholder.com/250
Can you paste the actual img src that's in your javascript?
I'm loading the jquery script at the top, not javascript. Maybe that's my problem. How would I add the source in jquery?
Why not just use vanilla JS? No reason to use jquery for that. But if you must, it'd prob be $('#image').src('')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.