transitionend event fires twice - javascript

I have the following code and my problem is that the transitionend event is fired twice. I don't know what's causing this. I suspected the vendor prefixes caused it, but they don't. Even if I only leave transitionend and transition it will still fire twice.
CSS
transition: 1s ease-out;
JS
document.addEventListener('click', function (e) {
var submarine = document.querySelector('.submarine');
var submarineX = e.clientX - submarine.offsetWidth / 2;
var submarineY = e.clientY - submarine.offsetHeight / 2;
submarine.style.left = submarineX + "px";
submarine.style.top = submarineY + "px";
});
document.addEventListener('transitionend', function (event) {
console.log(event.type + " " + new Date().getTime());
});
Fiddle
document.addEventListener('transitionend', function (event) {
console.log(event.type + " " + new Date().getTime());
});
document.addEventListener('click', function (e) {
var submarine = document.querySelector('.submarine');
var submarineX = e.clientX - submarine.offsetWidth / 2;
var submarineY = e.clientY - submarine.offsetHeight / 2;
submarine.style.left = submarineX + "px";
submarine.style.top = submarineY + "px";
});
.submarine {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
transition: 1s ease-out;
}
<div class="submarine"></div>

transitionend fires for each property transitioned, in your case top and left.
You can access the property associated with the event at event.propertyName.
There's no "transitionsend" event, so you will probably need some hackiness such as filtering the transitionend callback handling for only one of the transitioned properties. E.g.:
function (event) {
if (event.propertyName == 'top') {
//put your code here
}
});
ps. No browser fires the MSTransitionEnd event. It was at some point in the MS docs, but sometime before the IE10 beta release it was replaced by the standard transitionend event.

The event fires for each property that has been transitioned.
The propertyName way that Fabricio suggested is the proper way to do this, however if you are using jQuery you can also use one(); as well, like this.
$(document).one('transitionend webkitTransitionEnd MSTransitionEnd', function() {
...
});

For anyone looking for a simple, one time copy and paste solution (I've only included the necessary css). This doesn't answer the question and it does answer what I was looking for when I landed here.
CSS:
.my-elem {
transition: height 0.5s ease-out, opacity 0.5s ease-out;
}
JavaScript:
var elem = document.querySelector(".my-elem");
var transitionCounter = 0;
var transitionProp = window.getComputedStyle(elem , null)["transition-property"] || "";
// We just need to know how many transitions there are
var numTransitionProps = transitionProp.split(",").length;
elem.addEventListener("transitionend", (event) => {
// You could read event.propertyName to find out which transition was ended,
// but it's not necessary if you just want to know when they are all done.
if (transitionCounter < (numTransitionProps - 1)) {
transitionCounter++;
} else {
transitionCounter = 0; // reset
alert("I'm done!!!"); // do what you need to
}
}, false);
Tested in IE11, Chrome 48 and Firefox 37.

For anyone still looking for a more robust solution, like "allTransitionEnd" event, I've implemented a jQuery "special event", more as a proof of concept for something I was working on, but I might put out a lib on Github.
Check out the JSBin.
It's quite tricky, so I won't explain too much, but it makes it real easy to do stuff after ALL transitions have ended on an element:
$(function () {
$element.on('allTransitionEnd', function () {
// do something after all transitions end.
});
});
It works by probing the element for transition properties, then binds to the native transitionend events (vendor specific included) in order to keep track of properties that have finished transitioning. When all have finished transitioning it triggers any bound allTransitionsEnd handlers and then clears transition properties, in case they've changed as well, and probes for them fresh next time around.
This is really useful when multiple properties are being transitioned with varying delay and/or duration and you want to do something after all transitions have completed.
Example use cases:
Remove a flash message after fade-out and shrink.
Triggering "opened" and "closed" events in a reusable component, such as a menu or modal, where consumers may want to execute some logic after the transition has ended, without prying into css transitions.
If you are only transitioning one property, or have no varied delays and/or durations, then a simple solution works fine.
Works in latest version of Chrome, Firefox, Safari, Mobile Safari and IE11 and IE10. Doesn't work in IE8 because transitions are not supported. Bind to an additional native event as fallback.

You can use the target property to filter out events that are triggered by child elements and use propertyName to only trigger the event when a specific property changed.
const handleTransitionEnd = event => {
if (event.target !== myDomElementRef) return;
if (event.propertyName !== "height") return;
// Do my things
};

This is a relatively old question but I thought I'd share my answer:
function OnTransitionEvent() {
var t,
el = document.createElement('transitionElement');
var transitions = {
'transition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'MozTransition' : 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
for (t in transitions){
if (el.style[t] !== undefined){
return transitions[t];
}
}
}
var transitionEvent = OnTransitionEvent();
$(document).one(transitionEvent, function() {
console.log('done');
});

Related

Is there a way to detect that a css transition has been aborted/interruted?

According to the mdn transitionend doc, the transitionend event of a css transition won't be fired if the transition-property is removed or if the element (or one of its parent of course) becomes display:none.
I was wondering if there would be any way to detect such a case from javascript side (ie.: the transition has been interrupted). As far as i saw, there is no transitioninterrupted event or transitionaborted event, but maybe i missed something ?
Would you have any idea ?
Best regards
I tried to do a little research about it and there really are no other transition events other than transitionend, but i found this pen which tried to emulate a transitionstart event using a transitionend event which triggers after a very short delay.
Basing off that technique, I tried to emulate a transitioncancel event and got some "not bad" results. Here is the code for a little demo (explanation comes after):
HTML
<h1>Hello World</h1>
CSS
h1 {
margin-left: 0;
opacity: 0.99999;
transition: margin-left 1s ease, opacity 0.0001ms ease;
}
h1:hover {
opacity: 1;
margin-left: 500px;
}
Javascript
var h1 = document.querySelector('h1');
var styles = getComputedStyle(h1);
var duration = resolveDuration(styles.transitionProperty,
styles.transitionDuration);
var timer = null;
h1.addEventListener('transitionend', function(e) {
if (e.propertyName === 'opacity') {
timer = setTimeout(function() {
console.log('transition cancelled!');
}, duration);
} else {
clearTimeout(timer);
}
});
function resolveDuration(property, duration) {
var properties = property.split(/,\s+/g);
var durations = duration.split(/,\s+/g);
for (var i = 0; i < properties.length; i++) {
if (properties[i] !== 'opacity') {
var unit = durations[i].replace(/\d+\.?\d*/, '');
var value = parseInt(durations[i].replace(unit, ''));
if (unit === 's') {
return value * 1000;
}
return value;
}
}
return 0;
}
Explanation
Basically what this does is to start a setTimeout call after the emulated transitionstart, with the duration set to the transition-duration (which is normalized to milliseconds in the resolveDuration function).
When the function passed to setTimeout gets executed, it means that the transition got cancelled.
When another transitionend event gets emitted which is not for the opacity property (which is used to fake a transitionstart), the setTimeout call gets cancelled so that fake transitioncancel is not emitted.
Issues with this solution
There is a need for another transitioned property (opacity in this case) to fake the transitionstart.
Can only handle one transitioned property.
Fake transitioncancel only gets triggered after the transition-duration, and not immediately at the point when the transition got cancelled.
Check out this fiddle for a demo of this.

Photoswipe 4.0: Initiate 'swipe to next' programatically

SITUATION
I have been trying to trigger the 'slide to next picture' animation when the NEXT button is clicked, but i have not found a solution for this.
There is an ongoing discussion about this on GitHub, but it is only about adding the option for a slide animation, not about how to actually do it with PS as it is right now.
There was an option for it in 3.0 but as 4.0 is a complete rewrite it does not work anymore.
QUESTION
Instead of just 'jumping' to the next/prev picture when an arrow is clicked, i need the 'slide transition' that is also used when swiping/dragging the image.
There is no option to trigger that, so how can i manually trigger this effect with JS?
PhotoSwipe Slide Transitions
So, I added slide transitions to Photoswipe, and it's working nicely without disturbing native behavior.
http://codepen.io/mjau-mjau/full/XbqBbp/
http://codepen.io/mjau-mjau/pen/XbqBbp
The only limitation is that transition will not be applied between seams in loop mode (for example when looping from last slide to slide 1). In examples I have used jQuery.
Essentially, it works by simply adding a CSS transition class to the .pswp__container on demand, but we need to add some javascript events to prevent the transition from interfering with Swipe, and only if mouseUsed. We also add a patch so the transition does not get added between loop seams.
1. Add the below to your CSS
It will be applied on-demand from javascript when required.
.pswp__container_transition {
-webkit-transition: -webkit-transform 333ms cubic-bezier(0.4, 0, 0.22, 1);
transition: transform 333ms cubic-bezier(0.4, 0, 0.22, 1);
}
2. Add javascript events to assist in assigning the transition class
This can go anywhere, but must be triggered after jQuery is loaded.
var mouseUsed = false;
$('body').on('mousedown', '.pswp__scroll-wrap', function(event) {
// On mousedown, temporarily remove the transition class in preparation for swipe. $(this).children('.pswp__container_transition').removeClass('pswp__container_transition');
}).on('mousedown', '.pswp__button--arrow--left, .pswp__button--arrow--right', function(event) {
// Exlude navigation arrows from the above event.
event.stopPropagation();
}).on('mousemove.detect', function(event) {
// Detect mouseUsed before as early as possible to feed PhotoSwipe
mouseUsed = true;
$('body').off('mousemove.detect');
});
3. Add beforeChange listener to re-assign transition class on photoswipe init
The below needs to be added in your PhotoSwipe init logic.
// Create your photoswipe gallery element as usual
gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
// Transition Manager function (triggers only on mouseUsed)
function transitionManager() {
// Create var to store slide index
var currentSlide = options.index;
// Listen for photoswipe change event to re-apply transition class
gallery.listen('beforeChange', function() {
// Only apply transition class if difference between last and next slide is < 2
// If difference > 1, it means we are at the loop seam.
var transition = Math.abs(gallery.getCurrentIndex()-currentSlide) < 2;
// Apply transition class depending on above
$('.pswp__container').toggleClass('pswp__container_transition', transition);
// Update currentSlide
currentSlide = gallery.getCurrentIndex();
});
}
// Only apply transition manager functionality if mouse
if(mouseUsed) {
transitionManager();
} else {
gallery.listen('mouseUsed', function(){
mouseUsed = true;
transitionManager();
});
}
// init your gallery per usual
gallery.init();
You can just use a css transition:
.pswp__container{
transition:.3s ease-in-out all;
}
This might not be ideal for performance on mobile, but I just add this transition in a media query and allow users to use the swipe functionality on smaller screens.
I finally bit the bullet and spent some time making this work as nobody seemed to have a solution for that, not here neither on GitHub or anywhere else.
SOLUTION
I used the fact that a click on the arrow jumps to the next item and triggers the loading of the next image and sets the whole slide state to represent the correct situation in an instant.
So i just added custom buttons which would initiate a slide transition and then triggered a click on the original buttons (which i hid via CSS) which would update the slide state to represent the situation i created visually.
Added NEW next and prev arrows
Hid the ORIGINAL next and prev arrows via css
Animated the slide myself when the NEW next or prev arrows were clicked
Then triggered the click on the ORIGINAL next or prev arrows programmatically
So here is the code:
HTML
// THE NEW BUTTONS
<button class="NEW-button-left" title="Previous (arrow left)">PREV</button>
<button class="NEW-button-right" title="Next (arrow right)">NEXT</button>
// added right before this original lines of the example code
<button class="pswp__button pswp__button--arrow--left ...
CSS
pswp__button--arrow--left,
pswp__button--arrow--right {
display: none;
}
NEW-button-left,
NEW-button-right {
/* whatever you fancy */
}
JAVASCRIPT (helper functions)
var tx = 0; // current translation
var tdir = 0;
var slidepseactive = false;
// helper function to get current translate3d positions
// as per https://stackoverflow.com/a/7982594/826194
function getTransform(el) {
var results = $(el).css('-webkit-transform').match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))\))/)
if(!results) return [0, 0, 0];
if(results[1] == '3d') return results.slice(2,5);
results.push(0);
return results.slice(5, 8);
}
// set the translate x position of an element
function translate3dX($e, x) {
$e.css({
// TODO: depending on the browser we need one of those, for now just chrome
//'-webkit-transform': 'translate3d(' +String(x) + 'px, 0px, 0px)'
//, '-moz-transform': 'translate3d(' +String(x) + 'px, 0px, 0px)'
'transform': 'translate3d(' +String(x) + 'px, 0px, 0px)'
});
};
JAVASCRIPT (main)
// will slide to the left or to the right
function slidePS(direction) {
if (slidepseactive) // prevent interruptions
return;
tdir = -1;
if (direction == "left") {
tdir = 1;
}
// get the current slides transition position
var t = getTransform(".pswp__container");
tx = parseInt(t[0]);
// reset anim counter (you can use any property as anim counter)
$(".pswp__container").css("text-indent", "0px");
slidepseactive = true;
$(".pswp__container").animate(
{textIndent: 100},{
step: function (now, fx) {
// here 8.7 is the no. of pixels we move per animation step %
// so in this case we slide a total of 870px, depends on your setup
// you might want to use a percentage value, in this case it was
// a popup thats why it is a a fixed value per step
translate3dX($(this), tx + Math.round(8.7 * now * tdir));
},
duration: '300ms',
done: function () {
// now that we finished sliding trigger the original buttons so
// that the photoswipe state reflects the new situation
slidepseactive = false;
if (tdir == -1)
$(".pswp__button--arrow--right").trigger("click");
else
$(".pswp__button--arrow--left").trigger("click");
}
},
'linear');
}
// now activate our buttons
$(function(){
$(".NEW-button-left").click(function(){
slidePS("left");
});
$(".NEW-button-right").click(function(){
slidePS("right");
});
});
I used info from those SE answers:
jQuery animate a -webkit-transform
Get translate3d values of a div?
The PhotoSwipe can do this by itself when you use swipe gesture. So why not to use the internal code instead of something that doesn't work well?
With my solution everything works well, the arrow clicks, the cursor keys and even the loop back at the end and it doesn't break anything.
Simply edit the photoswipe.js file and replace the goTo function with this code:
goTo: function(index) {
var itemsDiff;
if (index == _currentItemIndex + 1) { //Next
itemsDiff = 1;
}
else { //Prev
itemsDiff = -1;
}
var itemChanged;
if(!_mainScrollAnimating) {
_currZoomedItemIndex = _currentItemIndex;
}
var nextCircle;
_currentItemIndex += itemsDiff;
if(_currentItemIndex < 0) {
_currentItemIndex = _options.loop ? _getNumItems()-1 : 0;
nextCircle = true;
} else if(_currentItemIndex >= _getNumItems()) {
_currentItemIndex = _options.loop ? 0 : _getNumItems()-1;
nextCircle = true;
}
if(!nextCircle || _options.loop) {
_indexDiff += itemsDiff;
_currPositionIndex -= itemsDiff;
itemChanged = true;
}
var animateToX = _slideSize.x * _currPositionIndex;
var animateToDist = Math.abs( animateToX - _mainScrollPos.x );
var finishAnimDuration = 333;
if(_currZoomedItemIndex === _currentItemIndex) {
itemChanged = false;
}
_mainScrollAnimating = true;
_shout('mainScrollAnimStart');
_animateProp('mainScroll', _mainScrollPos.x, animateToX, finishAnimDuration, framework.easing.cubic.out,
_moveMainScroll,
function() {
_stopAllAnimations();
_mainScrollAnimating = false;
_currZoomedItemIndex = -1;
if(itemChanged || _currZoomedItemIndex !== _currentItemIndex) {
self.updateCurrItem();
}
_shout('mainScrollAnimComplete');
}
);
if(itemChanged) {
self.updateCurrItem(true);
}
return itemChanged;
},

Resetting state of transition after the transition played

I have a message which I display on the screen when a user clicks on some links. I use a transition on the opacity to get the message to fade away.
The problem is that when a user clicks on the next link which is supposed to display the message, the element has its opacity set to 0 (thus it's not visible).
The opacity transition is triggered by a JavaScript function.
My question: would it be possible to reset the opacity (back to 1) before the transition effect happens?
I only see a nasty way such as triggering a function from within the function that triggers the opacity transition, to reset the opacity back to 1. Something like:
setTimeout(function(){elem.style.opacity = 1;)}, 3000);
But this is not great because I'd like the opacity to be reset as soon as a user clicks another link for which this message is displayed.
ideas?
EDIT:
Fiddle
HTML:
<div id="pop_up" class="pop_up">negative</div>
<a class="something_else" href="#" onclick="show(event, this); return false;">toto</a>
<a class="something_else" href="#" onclick="show(event, this); return false;">titi</a>
CSS:
.pop_up
{
position: absolute:
top: -10px;
padding: 10px;
background-color: orange;
opacity: 1;
transition: opacity 1s linear;
}
JS:
function show(e, elem)
{
msg = document.getElementById("pop_up");
msg.style.top = elem.offsetTop;
msg.style.left = elem.offsetLeft;
msg.style.opacity = 0;
msg.innerHTML = "Hug Me!";
}
I think I know what you want. You need to reset the transition to none and back again each time, and also reset the opacity each time and hide/show. Using the following CSS:
.pop_up
{
position: absolute;
display: none;
padding: 10px;
background-color: orange;
}
and the following javascript:
function show(e, elem) {
var msg = document.getElementById("pop_up");
msg.style.transition = 'none';
msg.style.display = 'none';
msg.style.opacity = 100;
msg.innerHTML = "Hug Me!";
msg.style.display = 'block';
msg.style.top = '' + elem.offsetTop + 'px';
msg.style.left = '' + elem.offsetLeft + 'px';
msg.style.transition = 'opacity 2s linear';
msg.style.opacity = 0;
}
I think you get the effect you want. I have changed to a 2s transition to see ity better, that you can adjust. The point is to hide and reset the popup each time, then reset the transition and show so that the transition runs again.
I have made msg a local vairable (with the vardeclaration) but also agree with the comments that using global functions and inline event handlers like this is not ideal. Improvments to that depnd on if you want to use a js library and if so which or if you want to stick to pure js.
Working fiddle (only tested in Firefox).
This technique stopped working with me, until I nailed done what actually make it work. It's necessary to keep this line in the JS code:
msg.style.bottom = elem.offsetTop + 'px';
If you remove it, it seems like the CSS for the element is not re-evaluated, which means the transition is actually not reset from 'none' to 'opacity 1s ease' for instance, which actually triggers the transition. So, if you remove the lines that actually reset the position of the div, the css won't be re-evaluated. In my case, I ended up needing the element to have a fixed position. So I first do:
msg.style.bottom = elem.offsetTop + 'px';
Immediately followed by:
msg.style.bottom = 0;
The first call internally forces the transition to be reset from none to something else, and then of course I finally positioned the element where I want.
Note that the first line might as well be:
var tmp = elem.offsetTop;
What's important here, is to change the state of the element, so that its CSS is being internally re-evaluated by the browser engine.

CSS Animations and page refresh on previous page with iOS/Android

I'm trying to achieve a transition effect when changing pages on a project I'm working on. The desired effect is the following:
Page fades in with an opacity from 0 to 1, thanks to a #keyframes
On any link clicked, the page opacity is changed back to 0, with another #keyframes
I've added an animationEnd event listener which will force the opacity of the page to 0 (in order to avoid a weird flash) and then will go to the link.
This is working fine on the latest versions of Chrome, FF and IE, but I'm having issues with iOS and Android. When hitting the "back" button, the page is showed with its latest state (opacity: 0). I believe this is a native solution which forces the CSS/JS not to reload again, but it's quite annoying as I can't find a way to "refresh" assets when hitting the "back" button.
Does anyones have a solid solution for this kind of issue ?
--
As an example, I've copied below a sample of my current JS :
if ("animation" in document.body.style) {
var animationEnd = "animationend"
}
else {
var animationEnd = "webkitAnimationEnd"
}
var link = document.querySelectorAll('a');
for (var i = 0; i < link.length; i++) {
link.item(i).addEventListener("click", function(e) {
var linktarget = this.getAttribute('href');
if (linktarget != '#') {
e.preventDefault();
page.className += ' ' + 'fadeout';
var fadeout = document.querySelector('.fadeout');
fadeout.addEventListener(animationEnd, function() {
this.style.opacity = '0';
window.location.href = linktarget;
});
}
});
}
Try wrapping your code you want to "refresh" into pageshow:
window.addEventListener("pageshow", function() {
... your code ...
}, false);

HTML5 dragleave fired when hovering a child element

The problem I'm having is that the dragleave event of an element is fired when hovering a child element of that element. Also, dragenter is not fired when hovering back the parent element again.
I made a simplified fiddle: http://jsfiddle.net/pimvdb/HU6Mk/1/.
HTML:
<div id="drag" draggable="true">drag me</div>
<hr>
<div id="drop">
drop here
<p>child</p>
parent
</div>
with the following JavaScript:
$('#drop').bind({
dragenter: function() {
$(this).addClass('red');
},
dragleave: function() {
$(this).removeClass('red');
}
});
$('#drag').bind({
dragstart: function(e) {
e.allowedEffect = "copy";
e.setData("text/plain", "test");
}
});
What it is supposed to do is notifying the user by making the drop div red when dragging something there. This works, but if you drag into the p child, the dragleave is fired and the div isn't red anymore. Moving back to the drop div also doesn't make it red again. It's necessary to move completely out of the drop div and drag back into it again to make it red.
Is it possible to prevent dragleave from firing when dragging into a child element?
2017 Update: TL;DR, Look up CSS pointer-events: none; as described in #H.D.'s answer below that works in modern browsers and IE11.
You just need to keep a reference counter, increment it when you get a dragenter, decrement when you get a dragleave. When the counter is at 0 - remove the class.
var counter = 0;
$('#drop').bind({
dragenter: function(ev) {
ev.preventDefault(); // needed for IE
counter++;
$(this).addClass('red');
},
dragleave: function() {
counter--;
if (counter === 0) {
$(this).removeClass('red');
}
}
});
Note: In the drop event, reset counter to zero, and clear the added class.
You can run it here
Is it possible to prevent dragleave from firing when dragging into a child element?
Yes.
#drop * {pointer-events: none;}
That CSS seem to be enough for Chrome.
While using it with Firefox, the #drop shouldn't have text nodes directly (else there's a strange issue where a element "leave it to itself"), so I suggest to leave it with only one element (e.g., use a div inside #drop to put everything inside)
Here's a jsfiddle solving the original question (broken) example.
I've also made a simplified version forked from the #Theodore Brown example, but based only in this CSS.
Not all browsers have this CSS implemented, though:
http://caniuse.com/pointer-events
Seeing the Facebook source code I could find this pointer-events: none; several times, however it's probably used together with graceful degradation fallbacks. At least it's so simple and solves the problem for a lot of environments.
It has been quite some time after this question is asked and a lot of solutions (including ugly hacks) are provided.
I managed to fix the same problem I had recently thanks to the answer in this answer and thought it may be helpful to someone who comes through to this page.
The whole idea is to store the evenet.target in ondrageenter everytime it is called on any of the parent or child elements. Then in ondragleave check if the current target (event.target) is equal to the object you stored in ondragenter.
The only case these two are matched is when your drag is leaving the browser window.
The reason that this works fine is when the mouse leaves an element (say el1) and enters another element (say el2), first the el2.ondragenter is called and then el1.ondragleave. Only when the drag is leaving/entering the browser window, event.target will be '' in both el2.ondragenter and el1.ondragleave.
Here is my working sample. I have tested it on IE9+, Chrome, Firefox and Safari.
(function() {
var bodyEl = document.body;
var flupDiv = document.getElementById('file-drop-area');
flupDiv.onclick = function(event){
console.log('HEy! some one clicked me!');
};
var enterTarget = null;
document.ondragenter = function(event) {
console.log('on drag enter: ' + event.target.id);
enterTarget = event.target;
event.stopPropagation();
event.preventDefault();
flupDiv.className = 'flup-drag-on-top';
return false;
};
document.ondragleave = function(event) {
console.log('on drag leave: currentTarget: ' + event.target.id + ', old target: ' + enterTarget.id);
//Only if the two target are equal it means the drag has left the window
if (enterTarget == event.target){
event.stopPropagation();
event.preventDefault();
flupDiv.className = 'flup-no-drag';
}
};
document.ondrop = function(event) {
console.log('on drop: ' + event.target.id);
event.stopPropagation();
event.preventDefault();
flupDiv.className = 'flup-no-drag';
return false;
};
})();
And here is a simple html page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Multiple File Uploader</title>
<link rel="stylesheet" href="my.css" />
</head>
<body id="bodyDiv">
<div id="cntnr" class="flup-container">
<div id="file-drop-area" class="flup-no-drag">blah blah</div>
</div>
<script src="my.js"></script>
</body>
</html>
With proper styling what I have done is to make the inner div (#file-drop-area) much bigger whenever a file is dragged into the screen so that the user can easily drop the files into the proper place.
Here, the simplest Cross-Browser solution (seriously):
jsfiddle <-- try dragging some file inside the box
You can do something like that:
var dropZone= document.getElementById('box');
var dropMask = document.getElementById('drop-mask');
dropZone.addEventListener('dragover', drag_over, false);
dropMask.addEventListener('dragleave', drag_leave, false);
dropMask.addEventListener('drop', drag_drop, false);
In a few words, you create a "mask" inside the dropzone, with width & height inherited, position absolute, that will just show when the dragover starts.
So, after showing that mask, you can do the trick by attaching the others dragleave & drop events on it.
After leaving or dropping, you just hide the mask again.
Simple and without complications.
(Obs.: Greg Pettit advice -- You must be sure that the mask hover the entire box, including the border)
This fairly simple solution is working for me so far, assuming your event is attached to each drag element individually.
if (evt.currentTarget.contains(evt.relatedTarget)) {
return;
}
The "right" way to solve this issue is to disable pointer events on child elements of the drop target (as in #H.D.'s answer). Here's a jsFiddle I created which demonstrates this technique. Unfortunately, this doesn't work in versions of Internet Explorer prior to IE11, since they didn't support pointer events.
Luckily, I was able to come up with a workaround which does work in old versions of IE. Basically, it involves identifying and ignoring dragleave events which occur when dragging over child elements. Because the dragenter event is fired on child nodes before the dragleave event on the parent, separate event listeners can be added to each child node which add or remove an "ignore-drag-leave" class from the drop target. Then the drop target's dragleave event listener can simply ignore calls which occur when this class exists. Here's a jsFiddle demonstrating this workaround. It is tested and working in Chrome, Firefox, and IE8+.
Update:
I created a jsFiddle demonstrating a combined solution using feature detection, where pointer events are used if supported (currently Chrome, Firefox, and IE11), and the browser falls back to adding events to child nodes if pointer event support isn't available (IE8-10).
if you are using HTML5, you can get the parent's clientRect:
let rect = document.getElementById("drag").getBoundingClientRect();
Then in the parent.dragleave():
dragleave(e) {
if(e.clientY < rect.top || e.clientY >= rect.bottom || e.clientX < rect.left || e.clientX >= rect.right) {
//real leave
}
}
here is a jsfiddle
A very simple solution is to use the pointer-events CSS property. Just set its value to none upon dragstart on every child element. These elements won't trigger mouse-related events anymore, so they won't catch the mouse over them and thus won't trigger the dragleave on the parent.
Don't forget to set this property back to auto when finishing the drag ;)
A simple solution is to add the css rule pointer-events: none to the child component to prevent the trigger of ondragleave. See example:
function enter(event) {
document.querySelector('div').style.border = '1px dashed blue';
}
function leave(event) {
document.querySelector('div').style.border = '';
}
div {
border: 1px dashed silver;
padding: 16px;
margin: 8px;
}
article {
border: 1px solid silver;
padding: 8px;
margin: 8px;
}
p {
pointer-events: none;
background: whitesmoke;
}
<article draggable="true">drag me</article>
<div ondragenter="enter(event)" ondragleave="leave(event)">
drop here
<p>child not triggering dragleave</p>
</div>
The problem is that the dragleave event is being fired when the mouse goes in front of the child element.
I've tried various methods of checking to see if the e.target element is the same as the this element, but couldn't get any improvement.
The way I fixed this problem was a bit of a hack, but works 100%.
dragleave: function(e) {
// Get the location on screen of the element.
var rect = this.getBoundingClientRect();
// Check the mouseEvent coordinates are outside of the rectangle
if(e.x > rect.left + rect.width || e.x < rect.left
|| e.y > rect.top + rect.height || e.y < rect.top) {
$(this).removeClass('red');
}
}
Very simple solution:
parent.addEventListener('dragleave', function(evt) {
if (!parent.contains(evt.relatedTarget)) {
// Here it is only dragleave on the parent
}
}
I was having the same issue and tried to use pk7s solution. It worked but it could be done a little bit better without any extra dom elements.
Basicly the idea is same - add an extra unvisible overlay over droppable area. Only lets do this without any extra dom elements. Here is the part were CSS pseudo-elements come to play.
Javascript
var dragOver = function (e) {
e.preventDefault();
this.classList.add('overlay');
};
var dragLeave = function (e) {
this.classList.remove('overlay');
};
var dragDrop = function (e) {
this.classList.remove('overlay');
window.alert('Dropped');
};
var dropArea = document.getElementById('box');
dropArea.addEventListener('dragover', dragOver, false);
dropArea.addEventListener('dragleave', dragLeave, false);
dropArea.addEventListener('drop', dragDrop, false);
CSS
This after rule will create a fully covered overlay for droppable area.
#box.overlay:after {
content:'';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 1;
}
Here is the full solution: http://jsfiddle.net/F6GDq/8/
I hope it helps anyone with the same problem.
You can fix it in Firefox with a little inspiration from the jQuery source code:
dragleave: function(e) {
var related = e.relatedTarget,
inside = false;
if (related !== this) {
if (related) {
inside = jQuery.contains(this, related);
}
if (!inside) {
$(this).removeClass('red');
}
}
}
Unfortunately it doesn't work in Chrome because relatedTarget appears not to exist on dragleave events, and I assume you're working in Chrome because your example did't work in Firefox. Here's a version with the above code implemented.
And here it goes, a solution for Chrome:
.bind('dragleave', function(event) {
var rect = this.getBoundingClientRect();
var getXY = function getCursorPosition(event) {
var x, y;
if (typeof event.clientX === 'undefined') {
// try touch screen
x = event.pageX + document.documentElement.scrollLeft;
y = event.pageY + document.documentElement.scrollTop;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return { x: x, y : y };
};
var e = getXY(event.originalEvent);
// Check the mouseEvent coordinates are outside of the rectangle
if (e.x > rect.left + rect.width - 1 || e.x < rect.left || e.y > rect.top + rect.height - 1 || e.y < rect.top) {
console.log('Drag is really out of area!');
}
})
Here's another solution using document.elementFromPoint:
dragleave: function(event) {
var event = event.originalEvent || event;
var newElement = document.elementFromPoint(event.pageX, event.pageY);
if (!this.contains(newElement)) {
$(this).removeClass('red');
}
}
Hope this works, here's a fiddle.
An alternate working solution, a little simpler.
//Note: Due to a bug with Chrome the 'dragleave' event is fired when hovering the dropzone, then
// we must check the mouse coordinates to be sure that the event was fired only when
// leaving the window.
//Facts:
// - [Firefox/IE] e.originalEvent.clientX < 0 when the mouse is outside the window
// - [Firefox/IE] e.originalEvent.clientY < 0 when the mouse is outside the window
// - [Chrome/Opera] e.originalEvent.clientX == 0 when the mouse is outside the window
// - [Chrome/Opera] e.originalEvent.clientY == 0 when the mouse is outside the window
// - [Opera(12.14)] e.originalEvent.clientX and e.originalEvent.clientY never get
// zeroed if the mouse leaves the windows too quickly.
if (e.originalEvent.clientX <= 0 || e.originalEvent.clientY <= 0) {
I know this is a old question but wanted to add my preference. I deal with this by adding class triggered css :after element at a higher z-index then your content. This will filter out all the garbage.
.droppable{
position: relative;
z-index: 500;
}
.droppable.drag-over:after{
content: "";
display:block;
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
z-index: 600;
}
Then just add the drag-over class on your first dragenter event and none of the child elements trigger the event any longer.
dragEnter(event){
dropElement.classList.add('drag-over');
}
dragLeave(event){
dropElement.classList.remove('drag-over');
}
Not sure if this cross browser, but I tested in Chrome and it solves my problem:
I want to drag and drop a file over entire page, but my dragleave is fired when i drag over child element. My fix was to look at the x and y of mouse:
i have a div that overlays my entire page, when the page loads i hide it.
when you drag over document i show it, and when you drop on the parent it handles it, and when you leave the parent i check x and y.
$('#draganddrop-wrapper').hide();
$(document).bind('dragenter', function(event) {
$('#draganddrop-wrapper').fadeIn(500);
return false;
});
$("#draganddrop-wrapper").bind('dragover', function(event) {
return false;
}).bind('dragleave', function(event) {
if( window.event.pageX == 0 || window.event.pageY == 0 ) {
$(this).fadeOut(500);
return false;
}
}).bind('drop', function(event) {
handleDrop(event);
$(this).fadeOut(500);
return false;
});
I've stumbled into the same problem and here's my solution - which I think is much easier then above. I'm not sure if it's crossbrowser (might depend on even bubbling order)
I'll use jQuery for simplicity, but solution should be framework independent.
The event bubbles to parent either way so given:
<div class="parent">Parent <span>Child</span></div>
We attach events
el = $('.parent')
setHover = function(){ el.addClass('hovered') }
onEnter = function(){ setTimeout(setHover, 1) }
onLeave = function(){ el.removeClass('hovered') }
$('.parent').bind('dragenter', onEnter).bind('dragleave', onLeave)
And that's about it. :) it works because even though onEnter on child fires before onLeave on parent, we delay it slightly reversing the order, so class is removed first then reaplied after a milisecond.
I've written a little library called Dragster to handle this exact issue, works everywhere except silently doing nothing in IE (which doesn't support DOM Event Constructors, but it'd be pretty easy to write something similar using jQuery's custom events)
Just check if the dragged over element is a child, if it is, then don't remove your 'dragover' style class. Pretty simple and works for me:
$yourElement.on('dragleave dragend drop', function(e) {
if(!$yourElement.has(e.target).length){
$yourElement.removeClass('is-dragover');
}
})
I wrote a drag-and-drop module called drip-drop that fixes this weirdo behavior, among others. If you're looking for a good low-level drag-and-drop module you can use as the basis for anything (file upload, in-app drag-and-drop, dragging from or to external sources), you should check this module out:
https://github.com/fresheneesz/drip-drop
This is how you would do what you're trying to do in drip-drop:
$('#drop').each(function(node) {
dripDrop.drop(node, {
enter: function() {
$(node).addClass('red')
},
leave: function() {
$(node).removeClass('red')
}
})
})
$('#drag').each(function(node) {
dripDrop.drag(node, {
start: function(setData) {
setData("text", "test") // if you're gonna do text, just do 'text' so its compatible with IE's awful and restrictive API
return "copy"
},
leave: function() {
$(node).removeClass('red')
}
})
})
To do this without a library, the counter technique is what I used in drip-drop, tho the highest rated answer misses important steps that will cause things to break for everything except the first drop. Here's how to do it properly:
var counter = 0;
$('#drop').bind({
dragenter: function(ev) {
ev.preventDefault()
counter++
if(counter === 1) {
$(this).addClass('red')
}
},
dragleave: function() {
counter--
if (counter === 0) {
$(this).removeClass('red');
}
},
drop: function() {
counter = 0 // reset because a dragleave won't happen in this case
}
});
I found a simple solution to this problem so sharing it. It works well in my case.
jsfiddle try it.
You can actually achieve this only via the dragenter event and you don't even need to register a dragleave. All you need is to have a no-drop area around your dropzones and that's it.
You can also have nested dropzones and this works perfectly. Check this as well nested dropzones.
$('.dropzone').on("dragenter", function(e) {
e.preventDefault();
e.stopPropagation();
$(this).addClass("over");
$(".over").not(this).removeClass("over"); // in case of multiple dropzones
});
$('.dropzone-leave').on("dragenter", function(e) {
e.preventDefault();
e.stopPropagation();
$(".over").removeClass("over");
});
// UPDATE
// As mar10 pointed out, the "Esc" key needs to be managed,
// the easiest approach is to detect the key and clean things up.
$(document).on('keyup', function(e){
if (e.key === "Escape") {
$(".over").removeClass("over");
}
});
After spending so many hours I got that suggestion working exactly as intended. I wanted to provide a cue only when files were dragged over, and document dragover, dragleave was causing painful flickers on Chrome browser.
This is how I solved it, also throwing in proper cues for user.
$(document).on('dragstart dragenter dragover', function(event) {
// Only file drag-n-drops allowed, http://jsfiddle.net/guYWx/16/
if ($.inArray('Files', event.originalEvent.dataTransfer.types) > -1) {
// Needed to allow effectAllowed, dropEffect to take effect
event.stopPropagation();
// Needed to allow effectAllowed, dropEffect to take effect
event.preventDefault();
$('.dropzone').addClass('dropzone-hilight').show(); // Hilight the drop zone
dropZoneVisible= true;
// http://www.html5rocks.com/en/tutorials/dnd/basics/
// http://api.jquery.com/category/events/event-object/
event.originalEvent.dataTransfer.effectAllowed= 'none';
event.originalEvent.dataTransfer.dropEffect= 'none';
// .dropzone .message
if($(event.target).hasClass('dropzone') || $(event.target).hasClass('message')) {
event.originalEvent.dataTransfer.effectAllowed= 'copyMove';
event.originalEvent.dataTransfer.dropEffect= 'move';
}
}
}).on('drop dragleave dragend', function (event) {
dropZoneVisible= false;
clearTimeout(dropZoneTimer);
dropZoneTimer= setTimeout( function(){
if( !dropZoneVisible ) {
$('.dropzone').hide().removeClass('dropzone-hilight');
}
}, dropZoneHideDelay); // dropZoneHideDelay= 70, but anything above 50 is better
});
"dragleave" event is fired when mouse pointer exits the dragging area of the target container.
Which makes a lot of sense as in many cases only the parent may be droppable and not the descendants.
I think event.stopPropogation() should have handled this case but seems like it doesn't do the trick.
Above mentioned some solutions do seem to work for most of the cases, but fails in case of those children which does not support dragenter / dragleave events, such as iframe.
1 workaround is to check the event.relatedTarget and verify if it resides inside the container then ignore the dragleave event as I have done here:
function isAncestor(node, target) {
if (node === target) return false;
while(node.parentNode) {
if (node.parentNode === target)
return true;
node=node.parentNode;
}
return false;
}
var container = document.getElementById("dropbox");
container.addEventListener("dragenter", function() {
container.classList.add("dragging");
});
container.addEventListener("dragleave", function(e) {
if (!isAncestor(e.relatedTarget, container))
container.classList.remove("dragging");
});
You can find a working fiddle here!
Solved ..!
Declare any array for ex:
targetCollection : any[]
dragenter: function(e) {
this.targetCollection.push(e.target); // For each dragEnter we are adding the target to targetCollection
$(this).addClass('red');
},
dragleave: function() {
this.targetCollection.pop(); // For every dragLeave we will pop the previous target from targetCollection
if(this.targetCollection.length == 0) // When the collection will get empty we will remove class red
$(this).removeClass('red');
}
No need to worry about child elements.
You can use a timeout with a transitioning flag and listen on the top element. dragenter / dragleave from child events will bubble up to the container.
Since dragenter on the child element fires before dragleave of the container, we will set the flag show as transitioning for 1ms... the dragleave listener will check for the flag before the 1ms is up.
The flag will be true only during transitions to child elements, and will not be true when transitioning to a parent element (of the container)
var $el = $('#drop-container'),
transitioning = false;
$el.on('dragenter', function(e) {
// temporarily set the transitioning flag for 1 ms
transitioning = true;
setTimeout(function() {
transitioning = false;
}, 1);
$el.toggleClass('dragging', true);
e.preventDefault();
e.stopPropagation();
});
// dragleave fires immediately after dragenter, before 1ms timeout
$el.on('dragleave', function(e) {
// check for transitioning flag to determine if were transitioning to a child element
// if not transitioning, we are leaving the container element
if (transitioning === false) {
$el.toggleClass('dragging', false);
}
e.preventDefault();
e.stopPropagation();
});
// to allow drop event listener to work
$el.on('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
});
$el.on('drop', function(e) {
alert("drop!");
});
jsfiddle: http://jsfiddle.net/ilovett/U7mJj/
I had a similar problem — my code for hiding the dropzone on dragleave event for body was fired contatantly when hovering child elements making the dropzone flicker in Google Chrome.
I was able to solve this by scheduling the function for hiding dropzone instead of calling it right away. Then, if another dragover or dragleave is fired, the scheduled function call is cancelled.
body.addEventListener('dragover', function() {
clearTimeout(body_dragleave_timeout);
show_dropzone();
}, false);
body.addEventListener('dragleave', function() {
clearTimeout(body_dragleave_timeout);
body_dragleave_timeout = setTimeout(show_upload_form, 100);
}, false);
dropzone.addEventListener('dragover', function(event) {
event.preventDefault();
dropzone.addClass("hover");
}, false);
dropzone.addEventListener('dragleave', function(event) {
dropzone.removeClass("hover");
}, false);
I struggeled a LOT with this, even after reading through all of these answers, and thought I may share my solution with you, because I figured it may be one of the simpler approaches, somewhat different though. My thought was of simply omitting the dragleave event listener completely, and coding the dragleave behaviour with each new dragenter event fired, while making sure that dragenter events won't be fired unnecessarily.
In my example below, I have a table, where I want to be able to exchange table row contents with each other via drag & drop API. On dragenter, a CSS class shall be added to the row element into which you're currently dragging your element, to highlight it, and on dragleave, this class shall be removed.
Example:
Very basic HTML table:
<table>
<tr>
<td draggable="true" class="table-cell">Hello</td>
</tr>
<tr>
<td draggable="true" clas="table-cell">There</td>
</tr>
</table>
And the dragenter event handler function, added onto each table cell (aside dragstart, dragover, drop, and dragend handlers, which are not specific to this question, so not copied here):
/*##############################################################################
## Dragenter Handler ##
##############################################################################*/
// When dragging over the text node of a table cell (the text in a table cell),
// while previously being over the table cell element, the dragleave event gets
// fired, which stops the highlighting of the currently dragged cell. To avoid
// this problem and any coding around to fight it, everything has been
// programmed with the dragenter event handler only; no more dragleave needed
// For the dragenter event, e.target corresponds to the element into which the
// drag enters. This fact has been used to program the code as follows:
var previousRow = null;
function handleDragEnter(e) {
// Assure that dragenter code is only executed when entering an element (and
// for example not when entering a text node)
if (e.target.nodeType === 1) {
// Get the currently entered row
let currentRow = this.closest('tr');
// Check if the currently entered row is different from the row entered via
// the last drag
if (previousRow !== null) {
if (currentRow !== previousRow) {
// If so, remove the class responsible for highlighting it via CSS from
// it
previousRow.className = "";
}
}
// Each time an HTML element is entered, add the class responsible for
// highlighting it via CSS onto its containing row (or onto itself, if row)
currentRow.className = "ready-for-drop";
// To know which row has been the last one entered when this function will
// be called again, assign the previousRow variable of the global scope onto
// the currentRow from this function run
previousRow = currentRow;
}
}
Very basic comments left in code, such that this code suits for beginners too. Hope this will help you out! Note that you will of course need to add all the event listeners I mentioned above onto each table cell for this to work.
Here is another approach based on the timing of events.
The dragenter event dispatched from the child element can be captured by the parent element and it always occurs before the dragleave. The timing between these two events is really short, shorter than any possible human mouse action. So, the idea is to memorize the time when a dragenter happens and filter dragleave events that occurs "not too quickly" after ...
This short example works on Chrome and Firefox:
var node = document.getElementById('someNodeId'),
on = function(elem, evt, fn) { elem.addEventListener(evt, fn, false) },
time = 0;
on(node, 'dragenter', function(e) {
e.preventDefault();
time = (new Date).getTime();
// Drag start
})
on(node, 'dragleave', function(e) {
e.preventDefault();
if ((new Date).getTime() - time > 5) {
// Drag end
}
})

Categories

Resources