skip to Main Content

I have an on click event on a parent element and an on click event on a child element. Each time I click on the child element, the on click associated with the parent element executes. Is there an easy way to allow my child element to be clickable?

<div class="main">
    <div>Some Content</div>
    <div>Some other Content</div>
    <div class="seeterms">See Terms & Conditions</div>
    ...
    <div class="terms">T&Cs</div>
</div>

$('.seeterms').on('click', function(){
$('html, body').scrollTop($(".terms").offset().top);
});

$('.main').on('click', function(){
    doSomething();
});

2

Answers


  1. const parentElement = document.getElementById('parent');
            const childElement = document.getElementById('child');
    
            parentElement.addEventListener('click', () => {
                console.log('Parent element clicked');
            });
    
            childElement.addEventListener('click', (event) => {
                event.stopPropagation(); // This prevents the click event from reaching the parent element
                console.log('Child element clicked');
            });
    #parent {
      width: 200px;
      height: 200px;
      background-color: lightgray;
    }
    
    #child  {
      width: 100px;
      height: 100px;
      background-color: lightblue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="parent">
            <div>Some Content</div>
        <div>Some other Content</div>
            <div id="child">
              <h1>See Terms & Conditions</h1>
             </div>
        </div>

    Use this type of script to make it work.

    Thanks.

    Login or Signup to reply.
  2. filter the clicked element using event.target, i mean you can know if the parent element clicked but the cursor actually clicked on child, you can do it using something like this:

    $('.parent').on('click', function(event){
        if ($(event.target).is($('.child'))) return;
        doSomething1();
    });
    
    $('.child').on('click', function(){
        doSomething2();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search