0

I am creating a div where you can drop files from your desktop, but also upload them by clicking on it. Because of the security limitations (I can't trigger a click for an file input), I am doing the trick of moving around an opacity 0 file input, following the mouse while it's on the target div. It perfectly works on Chrome, but Firefox doesn't do the trick (as it sticks the file input to the top left of the div. I'll show you the structure I am using:

<div style="position:relative;width:500px">
    <img class="img-drop" width="500" src="http://placehold.it/500x500">
    <div class="over-img-drop" style="position:absolute;width:100%;height:100%;top:0;">
        Drop or click to upload a picture.
        <input type="file" style="position:absolute;width:20px;height:20px;opacity:0" class="fileupload">
    </div>
    <a href="#" class="btn-statusbar" style="position:absolute;top:10px;right:10px"><i class="icon-chevron-down"></i></a>
</div>

And here comes the Javascript

<script type="text/javascript">
    $(".over-img-drop").on("mouseover,  mousemove", function(e){
        if($(e.target).hasClass("fileupload")) //if event is happening over file input, avoid moving
            return true;
        $(this).find(".fileupload").css("top", e.offsetY-10).css("left", e.offsetX-10);
            return false;
    });
</script>
Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93

1 Answers1

0

Well, I happened to find a solution:

event.offsetX and event.offsetY is available on Chrome, but not on Firefox (those values return undefined). What you have to do is to calculate the offset manually and put any position based on this calculations: jQuery includes this, as mentioned here.

What you should do is to get the container's offsets, and substract this from the event.pageX and event.pageY. So, the code looks like this:

<script type="text/javascript">
    $(".over-img-drop").on("mouseover,  mousemove", function(e){
        if($(e.target).hasClass("fileupload"))
            return true;
        var offsets = $(this).offset();
        $(this).find(".fileupload").css("top", e.pageY-offsets.top-10).css("left", e.pageX-offsets.left-10);
        return false;
    });
</script>
Community
  • 1
  • 1
Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93