Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Preventing child element from firing on click of Parent element

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.41k
    Comment on it

    Suppose, we have this html where div element have 2 child p elements and 1 child anchor element.

    <div>
        <p> I am para one</p>
        <p> I am para two</p>
        <a href="http:nowheretogo.com">I am a link</a>
    </div>
    

    lets add css that will differentiate between div, a and p tag

    div{ background:#abcdef; padding:20px; }
    p{ background:#00ff00; margin:20px; }
    a{ background:#00ff34; margin:20px; }
    

    Now if you want your jQuery function to run on div but not on elements inside the div (p an a tags here). use

    $('div').on('click', function(event) {
         if (event.target !== this) {
           event.preventDefault(); // for preventing anchor tag default functionality
           return;
        }else {
           alert('Make love not war');
        }
    });
    

    If you want to protect only one element inside div say anchor tag, here's how you can do it

    $("div").click(function(event) {
        if($(event.target).is('a')){
            event.preventDefault();
            return;
        }else {
           alert("Life is too short to grow old");
        }
    });
    

    here is a JSFiddle link for your experiments

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: