1

I am making a website using Bootstrap, Node.js, and jQuery for a club. I am trying to write a piece of Javascript code that when an image (or preferably the div it is in) is clicked on, another javascript function I have to change the pdf displaying will run. My problem is nothing works to catch a click on the image.

My code for the image:

<div id="2005d" style="cursor: pointer">
    <img id="2005p" style="max-width: 100%" src="/magazines/2005_cover.jpg">
    <h5 id="2005t" style="text-align: center; color: black">2005</h5>
</div>

The jQuery I am trying ot use to catch a click on this image:

$("document").ready(function() {
    $("#2005d").click(function(){
        alert("Clicked");
    });
});

What can I do to try to get jQuery to catch the click event on the image?

4
  • 1
    try $("#2005d").on('click', function(){...}); Commented Mar 1, 2018 at 3:58
  • 1
    The code you posted should work, do you get any errors on the console? At page loading or when you click the div? Commented Mar 1, 2018 at 3:58
  • 1
    Is there div in question loaded during page load or is it created dynamically? Try $(document).on("click", "#2005d", function() { //your stuff here}); Commented Mar 1, 2018 at 3:59
  • 1
    Since you have the click handler attached on the parent div(#2005d ), due to event bubbling any click events inside the child will be caught by the parent. Commented Mar 1, 2018 at 4:01

2 Answers 2

5

Use JQuery Event Delegation to set up the handler on the parent element, but test to see if the event originated on the image and use the JQuery .on() method instead of .click(), which JQuery recommends.

$("document").ready(function() {
    $("#2005d").on("click", "img" ,function(){
        alert("Clicked");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="2005d" style="cursor: pointer">
    <img id="2005p" style="max-width: 100%" src="https://image.spreadshirtmedia.com/image-server/v1/mp/designs/12386804,width=178,height=178/winking-smiley-face.png">
    <h5 id="2005t" style="text-align: center; color: black">2005</h5>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

your code is right but you have to write click event for image,, try this it works

$("document").ready(function() {
 $("#2005p").click(function(){
    alert("Clicked");
 });
});

Comments

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.