Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why loop formed after click on div?

I have styled file input:

<div class="fakeFileContainer">
 <div class="fakeFile">Dołącz brief</div>
 <input id="file" type="file" name="file"/>
</div>

for this part of code I have some line of js:

var fileInput = $('#contact #file')

fileInput.change(function(){
    $this = $(this);
    $('#contact form .fakeFile').text($this.val());
})

$('#contact form .fakeFileContainer').on('click', function () {
    fileInput.click(); //looping here
}).show();

After click on .fakeFileContainer I've got this error msg in console:

Uncaught RangeError: Maximum call stack size exceeded

It's caused by loop, but I don't know why this loop formed here. Can comeone explain me reason of this situation?



P.S. Please excuse any spelling or grammatical mistakes, English isn't my first language
like image 804
WooCaSh Avatar asked Dec 26 '22 09:12

WooCaSh


2 Answers

Your clicks on fileInput are handled by that function too (because the even bubbles up to the container). So the code says: "when clicked, trigger another click event". That second click event causes the same question to be asked again, and the answer is, again, to fire another click event. Thus, an infinite loop.

like image 195
bfavaretto Avatar answered Jan 11 '23 22:01

bfavaretto


The triggered click event bubbles up, and you catch it right on the parent element to trigger the next click - creating an infinite loop. To prevent this, you can either

  • stopPropagation of click events on the input
  • do not trigger clicks if the handled event was issued on the input (by checking the srcElement)
  • or put the click handler on the .fakeFile div instead of the surrounding container.
like image 22
Bergi Avatar answered Jan 11 '23 23:01

Bergi