Ari
Ari

Reputation: 21

Replace image on mouse click using jQuery and Django doesn't work

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?

Upvotes: 1

Views: 316

Answers (2)

Onkar
Onkar

Reputation: 2584

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 );
    });
});

Upvotes: 0

react_or_angluar
react_or_angluar

Reputation: 1574

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>

Upvotes: 1

Related Questions