1

I have simple div with one element:

<div id="drop-zone">
    <input type="file" style="display: none;" multiple="multiple">
</div>

When I click on #drop-zone I want to trigger input manually. I'm trying like this:

jQuery('#drop-zone:not(input)').click(function() {
    jQuery(this).find('input[type="file"]').trigger('click')
})

The main problem is that I'm getting an endless loop of clicks as my manual click trigger listener on parent element.

user1692333
  • 2,461
  • 5
  • 32
  • 64
  • 2
    Possible duplicate of [jquery stop child triggering parent event](https://stackoverflow.com/questions/2364629/jquery-stop-child-triggering-parent-event) – vmf91 Mar 10 '19 at 13:56

2 Answers2

0

Make sure that the element clicked was the drop-zone by checking the id of the target. When jQuery emulates an event it will pass the same this reference but will not pass the event, so just check if the event is set.

$("#drop-zone").click(function(event) {
  if (this.id === "drop-zone" && event.originalEvent) {
    $("#drop-zone>input").trigger("click");
  }
})
#drop-zone {
  background-color: red;
  height: 50px;
  width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="drop-zone">
  <input type="file" style="display: none;" multiple="multiple">
</div>

You could also just trigger the event manually.

$("#drop-zone").click(function(event) {
  if (this.id === "drop-zone") {
    $("#drop-zone>input")[0].click();
  }
})
#drop-zone {
  background-color: red;
  height: 50px;
  width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="drop-zone">
  <input type="file" style="display: none;" multiple="multiple">
</div>
nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

Maybe this is what you want:

var x_m = 0;
var y_m = 0;
$('#drop-zone').click(function(event) {
  var mtarget = document.elementFromPoint(x_m, y_m);
  if (mtarget.id === "drop-zone") {
    var input = $(this).find('input[type="file"]');
    var h = false;
    if ($(input).is(":visible")) {
      input.hide();
    } else {
      input.show();
      h = true;
    }
    console.log("You clicking, the #drop-zone, input.visible =>", h);
  } else { 
    console.log("You clicking the input.");
  }
})
$('body').mousemove(function(evt){
    x_m = evt.pageX;
    y_m = evt.pageY;
});
#drop-zone {
  height: 40px;
  width: 250px;
  background-color: #8b5fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="drop-zone">
  <input type="file" style="display: none; background: green;" multiple="multiple">
</div>
BladeMight
  • 2,670
  • 2
  • 21
  • 35