David
David

Reputation: 4281

Parent element event is fireing on click of child element

I have created a checkbox and PLacing it on myElement. Here is my code.

var myCheckBox = document.createElement("input");
    myCheckBox.setAttribute("type", "checkbox");
    myCheckBox.innerHTML = "";
    myCheckBox.setAttribute("id", "myID");
    myCheckBox.onchange = CheckBoxChange;
    myCheckBox.setAttribute("value", title);
    myEle.insertBefore(myCheckBox, myEle.firstChild);

NOw onclick of myEle some another event like sorting is happening. SO when check/Unckeck checkbox the paraent element event is also fiering. How to overcome from that.

What I am trying here is

function CheckBoxChange(e){
    e.stopPropagation();
}

But before my trigger reach at CheckBoxChange the event of myEle get fierd. How I can restrict that event upto myEle and it not come to checkbox. Thanks for help.

Upvotes: 2

Views: 112

Answers (1)

nnnnnn
nnnnnn

Reputation: 150030

When you click on the checkbox that causes a click event and a change event, both of which bubble up to the container.

In your code, you stop propagation of the change event, but not the click event. I am guessing that your parent myEle has a click handler to trigger the sorting you mention.

If you change your checkbox to use a click handler instead of change that should behave the way you want, as you can see here: http://jsfiddle.net/wqdcd41p/. (Note that even if you check/uncheck a checkbox via the keyboard a click event will still be triggered.)

Upvotes: 2

Related Questions