1

I want to replace an image when it is clicked using jQuery. Here is my code.

HTML

{% load static %}
<div class="col-md-6 image">
    <img class="map" src="{% static 'home/map.png' %}" class="doctors">
</div>

jQuery

$(document).ready(function() {
    $('.map').click(function() {
        $(this).attr("src", "{% static 'home/map2.png' %}");
    });
})

I tried the code above and it didn't work. The location of the image and its image format is already correct but when I click the image it only shows a blank picture (the same display as when we write the wrong image format).

I already tried to change the jQuery into this one too

$('.map').click(function() {
    $(this).attr("src", "home/map2.png");
});

but it still didn't work. Anyone knows how to fix it?

react_or_angluar
  • 1,568
  • 2
  • 13
  • 20
Ari
  • 21
  • 2
  • Can you try to make your code run like this? https://jsfiddle.net/rabiee3/ftkuub3j/ Is this helpful? https://stackoverflow.com/a/12784242/3825777 – react_or_angluar Dec 27 '20 at 09:40
  • 1
    Hello so apparently my code works when I change the source with url of images online, thank u for your answer!:) – Ari Dec 27 '20 at 09:53

2 Answers2

1

Here is your solution in a runnable stack-snippet.

$(document).ready(function() {
    $('.map').click(function() {
        var img2 = $(this).attr("data-img2");
        $(this).attr("src", img2);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6 image">
       <img class="map" data-img2="https://homepages.cae.wisc.edu/~ece533/images/arctichare.png" src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png"> 
</div>
react_or_angluar
  • 1,568
  • 2
  • 13
  • 20
0

Use something like to avoid JS errors along with liquid code


HTML

{% load static %}
<div class="col-md-6 image">
    <img class="map" data-img2="{% static 'home/map2.png' %}" src="{% static 'home/map.png' %}" class="doctors">
</div>

jQuery

$(document).ready(function() {
    $('.map').click(function() {
        var img2 = $(this).attr("data-img2");
        $(this).attr("src", img2 );
    });
});
Onkar
  • 2,409
  • 2
  • 11
  • 14