MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29176

Javascript: setting up proper event handler for elements

I have a DOM structure which looks something like below -

<div id='MyDiv'>
    <span>Hello MyDiv</span>
    <p class='MyClass'>
        <img src='image.png' alt='myImage' width='300px' height='300px' />
        <a href='#goToNextDiv'>Go to next</a>
    </p>
</div>

Now MyDiv has a click event handler attached with prototype library, the source of which isn't accessible to me. I want to remove this handler from the div and insert another one. I've tried the following code for this -

var content = document.getElementById('MyDiv');
content.addEventListener('click', function(event){
    event.preventDefault();
    event.stopPropagation();

    alert('This is my handler');    

    return false;
}, true);

The problem is, this code also prevents the click event of the anchor tag. Clicking on the div causes my event handler to execute, which is desired, but it also stops the anchor tag to execute it's normal behavior (which is jumping to the div goToNextDiv).

Now I have tried commenting out the event.stopPropagation() line, which again enables the event propagation and allows the anchor to behave accordingly, but then it also executes the previous click event handler of MyDiv.

How can I remove the previous handler from the div and attach my new one so that -

  1. the previous event handler for the div doesn't get called
  2. my div event handler executes
  3. the anchor tag also works (there could be many anchor tags inside the div, in any place)

Upvotes: 1

Views: 230

Answers (1)

Musa
Musa

Reputation: 97717

You can check if the click target was an anchor and not prevent the default action.

var content = document.getElementById('MyDiv');
content.addEventListener('click', function(event){
    if (event.target.tagName != 'A'){//or some other way to tell if it is a link
        event.preventDefault();
        event.stopPropagation();

        alert('This is my handler');    

        return false;
    }
}, true);

Upvotes: 2

Related Questions