0

In my main python file, I have the following code.

@app.route('/accounts/test/learn/medium')
def medium():
word = random.choice(os.listdir("characters/"))
return render_template('accounts/test/medium.html', word=word)

My HTML Template "Medium" has a div called "character" which contains the word.

<div id="character" style="font-weight:bold;color:red"  >{{ word }}</div>

My Javascript file, which I call body onLoad tries to set the png file for the word/character.

currentWord = document.getElementById("character").value
if(document.getElementById("characterPNG")!=null){
    document.getElementById("characterPNG").src = "../../../style/images/characters/png/" +currentWord+ ".png";

When I run the application, Python sets the word in my HTML I can see that, but JavaScript, can't see the value of character. It rather say's

Failed to load resource: the server responded with a status of http://path/undefined.png

Do you have any suggestions what might be wrong? Is it the sequence?

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
  • 1
    The JavaScript is running in the browser on the client side; you can't use a relative path for the image. You should use flask to supply the image URL with `url_for`. – jonrsharpe Jan 08 '17 at 15:30
  • I think the main issue is that the DIV-element does not have a value. He wants to read the HTML content (the `innerHTML` attribute) – DiKorsch Jan 08 '17 at 16:02

2 Answers2

1

According to this answer Get content of a DIV using JavaScript you should use innerHTML instead of value:

currentWord = document.getElementById("character").innerHTML
Community
  • 1
  • 1
DiKorsch
  • 1,240
  • 9
  • 20
0

As pointed out in the comments, I would make good use of url_for from Flask to generate urls for static files, as follows:

Quoting from Flask's doc:

Static Files

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

So, after you create a static folder, just reference it in your template with url_for method pointing out as well the filename:

<img id="characterPNG" src={{url_for('static', filename=word+'.png')}}></img>
Iron Fist
  • 10,739
  • 2
  • 18
  • 34