1

scripts.js code:

$(document).ready(function(){
    $('#user').hover(function() {
        $('#user img').attr('src', "{% static 'images/user_selected.png' %}");
    }, function() {
        $('#user img').attr('src', "{% static 'images/user.png' %}");
    });
});

It works fine when I write it directly in my base.html file, but when I place it in an external .js file it fails to load images.

Scripts.js file loads but images do not.

base.html code:

<head>
    ...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="{% static 'js/scripts.js' %}"></script>
    ...
</head>
<body>
    ...
    <a href="{%url 'logout' %}">LOG OUT</a>
    <a id="user" href="#">
        <img src="{% static 'images/user.png' %}" />
        <span id="user-name">{{request.user.username}}</span>
    </a>
    ...
</body>
0

1 Answer 1

3

The problem is because the templating syntax you're using (ie. {% static 'images/user_selected.png' %}), will not be interpreted in a JS file.

To work around this you can put the image sources in data attributes on the img in the HTML which can then be read in the external JS, like this:

jQuery($ => {
  $('#user').hover(function() {
    $(this).children('img').prop('src', function() {
      return $(this).data('over');
    });
  }, function() {
    $(this).children('img').prop('src', function() {
      return $(this).data('leave');
    });
  });
});
<a id="user" href="#">
  <img src="{% static 'images/user.png' %}" data-over="{% static 'images/user_selected.png' %}" data-leave="{% static 'images/user.png' %}" height="14px" width="14px" id="user-icon" />
  <span id="user-name">{{request.user.username}}</span>
</a>
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly. Thank you!
No problem, glad to help

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.