Question

I have found many solutions here how to prevent the children from running the assigned event handler when clicked but the issue here is that they still execute that handler until the function returns. Now, I have some input fields there and their native click handler does not execute, its overwritten. So an input file field does not open the file browser but runs the assigned event handler to the parent div. It seems even google does not know the answer (or I just use the wrong keywords), you guys know any solution?

Here is some code to test: http://jsfiddle.net/Mu58z/2/

<!DOCTYPE html><html><head></head><body>
  <div id="myContainer">
    <input type="file" />
    <input type="file" />
  </div>
<script type="text/javascript">
var count = 0;
var myEventHandler = function(e) {
e.stopPropagation();
e.preventDefault();
alert(++count + ' times fired');
}

// that variable is already set and I cannot find the element
var foo = $('#myContainer');

// try these, none of them works as intended
//foo.on('click', myEventHandler);
foo.filter(':not(input:file)').on('click', myEventHandler);
</script>
</body>
</html>
Was it helpful?

Solution

Solved. When I clicked on the input button it also fired the parent's event handler due to propagation, the solution is ridiculously simple. I've never overwritten the input's event handler.

http://jsfiddle.net/Mu58z/2/

$('input:file').on('click', function () { 
  e.stopPropagation();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top