Ayush Baheti Ayush Baheti - 3 months ago 8
Javascript Question

jQuery .on click event handler for img

I am trying to call a function on clicking an image using jQuery.

My html code is as follows:

<div id="fixed-navbar">
<div class="nav-left">
<img id="back" src="back.png">
</div>
... (some other code)
</div>


to call a function on clicking of the above image i am writing script as:

$("#back").on('click', '.nav-left', function(e) {
e.preventDefault();
window.history.back();
});


why isn't this working?

PS: These div's are added dynamically

Answer

You're binding the event on .nav-left instead of #back itself.

$("#back").on('click', function(e) {
    e.preventDefault();
    window.history.back();
});

If your image is dynamically generated inside the div.nav-left element, you just need to reverse the selectors.

$(".nav-left").on('click', '#back', function(e) {
    e.preventDefault();
    window.history.back();
});

If all your content is dynamic, you need to do it this way.

$("body").on('click', '#back', function(e) {
    e.preventDefault();
    window.history.back();
});

Instead of body, you can specify the closest enclosing parent element that is not dynamically added to the page.