Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if jQuery clicked element an anchor containing an img

How can I check if the clicked element was an anchor containing an img?

So for example I want to check if this element was clicked:

<a href="#">
    <img src="#" />
<a/>
jQuery(document).click(function(e) {
    // e.target.hereIsWhereINeedHelp;
});

Thanks in advance!

like image 804
user1878980 Avatar asked Apr 15 '15 15:04

user1878980


2 Answers

If you wish to capture the "click" from any element:

jQuery(document).click(function(e) {
    if (jQuery(e.target).is('a') && jQuery(e.target).has('img')) {
        // code goes here
    }    
});

Whether you choose to prevent the "default behavior" is another question.

like image 75
ne1410s Avatar answered Oct 12 '22 06:10

ne1410s


You can use .is("a") and .has("img"):

<a href="#">
   <img src="#" />
<a/>

<script>
    jQuery(document).click(function(e) {
        var target = $( e.target );
        if ( target.is( "a" ) && target.has("img") ) {
            //Do what you want to do
        }
    });
</script>
like image 40
Tdy Avatar answered Oct 12 '22 04:10

Tdy