Places an event inside an event, does it have a name?
He has a name. Bad idea . Let me run away. What happens when you execute the following code.
$('#button').click(function(){ console.log('CLICK IN FIRST INPUT FILE!'); });
A click event is registered on a button. Once an event is registered, it will fire every time, no matter how many times you click.
When you put this code inside another event handler, as in the first example, it runs every time the input files are changed and a new event handler is registered. Therefore, when you select a file, and then decide to change it, changes to the file are entered twice, and you register 2 registered events. Now press the button, you will get 2 new console logs printed with one click !!! Give it a try.
Why is the click event of the first input file executed if there is no event change?
Because, as the event handler works, you register once, after that they are launched every time after that.
Which of the two methods is better (and the most correct) for running the code, and why?
Obviously not the first, because it is a bad idea, not the second. In the case of the second, you attach the event to the division, which will contain the button. Thus, you do not need to click on the button, just click on any right side of the button, the event will be fired !!!
So, if none of them are right, what can we do?
- Do not create a button / any html javascript element for such simple tasks. Do it with HTML, simple and simple.
- Do not embed an event handler in another. Put one event handler inside another, this will complicate the situation. Just put all the event handlers directly inside the document.ready jQuery event. document.ready only fires once.
- When you need to control user action, then show / hide your button or other html element using javascript based on the required conditions.
My suggestion is doing something like this.
$(document).ready(function(){ // Hide the button at first $('#button').hide(); // When File-input changes $('#file').change(function(){ if(**the file-input has a file selected**){ $('#button').show(); } else{ $('#button').hide(); } }); // When Button Clicked $('#button').click(function(){ // Do the action }); });