user6159172
user6159172

Reputation:

How to add a click function on an image

I am trying to write a function so that when I click on an image it loads external content.

<section class='images'>
<img class="review-img" id="lifeofpi" src="./images/lifeofpi.jpg"></img>
</section>

    $(document).ready(function(){
    $("#lifeofpi").click(function(){
        $("#lifeofpi").load("lifeofpi.txt #p1");
    });
});

When I click on the image I want it to load this external content from a text document. But when I click on the image nothing happens.

Upvotes: 0

Views: 54

Answers (2)

Harshpreet Singh
Harshpreet Singh

Reputation: 16

$("#lifeofpi").on("click","#p1 lifeofpi.txt",function (e) {
e.preventDefault();
alert(this.id);
});

Read about event-delegation

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You are trying to load content into the image. You need to add it to an element that can actually have children.

<section class='images'>
  <img class="review-img" id="lifeofpi" src="./images/lifeofpi.jpg">
  <div id="lifeofpi_details"></div>
</section>

    $(document).ready(function(){
    $("#lifeofpi").on("click", function () {
        $("#lifeofpi_details").load("lifeofpi.txt #p1");
    });
});

Upvotes: 1

Related Questions