Get incorrect offsetWidth and offsetHeight values - html

Here is my angular2 code.
Template
<div #picker class="slider">
<div class="slider-track">
<div #sliderSelectionEl class="slider-selection"></div>
<div #sliderHandle1 class="slider-handle"></div>
<div #sliderHandle2 class="slider-handle"></div>
</div>
<div #tooltipEl class="tooltip">
<div class="tooltip-arrow"></div>
<div #tooltipInner class="tooltip-inner"></div>
</div>
<input type="text" class="span2" value="" id="sl2"><br/>
</div>
Component
import {Component, OnInit, Input, ViewChild, ElementRef, Renderer} from '#angular/core';
export class SliderComponent implements OnInit {
#ViewChild('picker') picker: ElementRef;
constructor(private renderer: Renderer, private el: ElementRef) {
}
ngAfterViewInit() {
this.renderer.setElementClass(this.picker.nativeElement, 'slider-horizontal', true);
console.log(this.picker.nativeElement.offsetWidth);
console.log(this.picker.nativeElement.offsetHeight);
}
}
.slider-horizontal {
width: 210px;
height: 20px;
}
The problem is the printed values are different for each time loading. I guess this issue is due to the browser have not completed loading the div. Do you know what is the solution for this?

You can detect size changes by using
MutationObserver
Probably the biggest audience for this new api are the people that
write JS frameworks, [...] Another use case would be situations where you are using frameworks that manipulate the DOM and need to react to these
modifications efficiently ( and without setTimeout hacks! ).
Here is how you can use it to detect changes in elements :
// select the target node
var target = document.querySelector('#some-id'); // or
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
For your case, you could use it inside your ngAfterViewInit and refresh your offsets size. You can be more specific and only detect some mutations, and only then extract your offsets.
more info :
doc: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
compatibility : https://caniuse.com/#feat=mutationobserver
Demo:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
if(mutation.attributeName == 'class') // detect class change
/*
or if(mutation.target.clientWidth == myWidth)
*/
showOffset(mutation.target);
observer.disconnect();
});
});
var config = { attributes: true}
var demoDiv = document.getElementById('demoDiv');
var logs = document.getElementById('logs');
// wait for document state to be complete
if (document.readyState === "complete") {
ngAfterViewInit();
}
document.onreadystatechange = function () {
if (document.readyState === "complete") {
ngAfterViewInit();
}
}
// observe changes that effects demoDiv + add class
function ngAfterViewInit(){
observer.observe(demoDiv, config);
demoDiv.classList.add('slider-horizontal');
}
// show offsetWidth + height.
// N.B offset width and height will be bigger than clientWidth because I added a border. If you remove the border you'll see 220px,20px
function showOffset(element){
offsetMessage = "offsetWidth:" + demoDiv.offsetWidth + " offsetHeight: " + demoDiv.offsetHeight;
console.log(offsetMessage);
logs.innerHTML = offsetMessage;
}
.slider-horizontal {
border: 2px solid red;
width: 210px;
height: 20px;
background: grey;
}
<div id='demoDiv'> I am a demo div </div>
<div style="margin-top: 20px;"> logs : <span id='logs' style=" padding: 5px; border: 1px solid black"></span></div>

You have to schedule calls to 'offsetWidth' after rendering cycle, angular executes draw on the end of microtask queue, so you could try setTimeout(..., 0) or run Promise.resolve().then(...) outside of zonejs. Hope it helps.

In order to get correct offset values you can use: ngAfterContentChecked with the AfterContentChecked Interface.
This method is called after every change detection run. So, inside this method use a flag (or counter) and setTimeOut:
if (this.counter <= 10) {
// this print offsetwidth of my element
console.log('mm ' + this.container.nativeElement.offsetWidth);
// setTimeOut allow to run another changedetection
// so ngAfterContentChecked will run again
setTimeout(() => { }, 0);
//you could use a counter or a flag in order to stop getting the right width
this.counter++;
}
Hope it helps! Feel free to comment

Related

Extending native HTML element in Angular 6

I have recently created a native web component which is working well in all browsers. I moved this web component into an Angular 6 application and all works as expected. I then tried to extend a native HTML element which again worked perfectly except when I brought it into my Angular 6 application.
Using the examples from Mozilla I will try and illustrate my issue. Using the following trying to extend a native 'p' element:
// Create a class for the element
class WordCount extends HTMLParagraphElement {
constructor() {
// Always call super first in constructor
super();
// count words in element's parent element
var wcParent = this.parentNode;
function countWords(node){
var text = node.innerText || node.textContent
return text.split(/\s+/g).length;
}
var count = 'Words: ' + countWords(wcParent);
// Create a shadow root
var shadow = this.attachShadow({mode: 'open'});
// Create text node and add word count to it
var text = document.createElement('span');
text.textContent = count;
// Append it to the shadow root
shadow.appendChild(text);
// Update count when element content changes
setInterval(function() {
var count = 'Words: ' + countWords(wcParent);
text.textContent = count;
}, 200)
}
}
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
<p is="word-count">This is some text</p>
By taking that same code and putting it into an Angular 6 application, the component never runs. I put console log statements in the constructor and connectedCallback methods and they never trigger. If I remove the {extends: 'p'} object and change the extends HTMLParagraphElement and make it an extend HTMLElement to be an autonomous custom element everything works beautifully. Am I doing something wrong or does Angular 6 not support the customized built-in element extension?
I assume the reason is the way that Angular creates those customized built-in elements when parsing component templates - it probably does not know how to properly do that. Odds are it considers is a regular attribute which is fine to add after creation of the element (which it isn't).
First creating the element and then adding the is-attribute will unfortunately not upgrade the element.
See below example: div#d has a non-working example of that customized input.
customElements.define('my-input', class extends HTMLInputElement {
connectedCallback() {
this.value = this.parentNode.id
this.parentNode.classList.add('connected')
}
}, {
extends: 'input'
})
document.addEventListener('DOMContentLoaded', () => {
b.innerHTML = `<input type="text" is="my-input">`
let el = document.createElement('input', {
is: 'my-input'
})
el.type = 'text'
c.appendChild(el)
// will not work:
let el2 = document.createElement('input')
el2.setAttribute('is', 'my-input')
el2.type = 'text'
d.appendChild(el2)
})
div {
border: 3px dotted #999;
padding: 10px;
}
div::before {
content: "#"attr(id)" ";
}
.connected {
background-color: lime;
}
<div id="a"><input type="text" is="my-input"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
So to get it to work with Angular, hook into the lifecycle of your Angular component (e.g. onInit() callback) and pick a working way to create your element there.

Why css styles behave that way?

I created small app using angular-cli based on 'Getting Started with Reactive Programming Using RxJS by Scott Allen' on Pluralsight. It creates Observable stream of events from mouse. Nothing fancy - stream of data works nice. The only problem is that styles are applied in a weird way for me. They update div only 2 times in an unknown way.
They are changed to 0px - once for x, once for y axis, when I move a mouse in an area of circle. One time and that's it. I changed manually these attributes in Developer Tools and it works like it should. But cannot laverage this behaviour automatically.
css html
#circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
position: absolute;
}
<div id="circle"></div>
Typescript
ngOnInit() {
let circle = document.getElementById('circle')
let mouse = fromEvent(document, 'mousemove')
.pipe(
map((e: MouseEvent) => {
return {
x: e.clientX,
y: e.clientY
}
}),
)
function onNext(value) {
circle.style.left = value.x
circle.style.top = value.y
console.log("xy", value.x, value.y)
}
mouse.subscribe(
value => onNext(value),
e => console.log(`error: ${e}`),
() => console.log('complete.')
)
}
add 'px' to value:
function onNext(value) {
console.log(circle.style.left)
circle.style.left = value.x + 'px'
circle.style.top = value.y + 'px'
console.log("xy", value.x, value.y)
}
and circle will change position by mouse. DEMO

Is it possible to detect the end of the last CSS transition when multiple are running?

If an element has more than one of its css properties changed and they have differing transition durations, is there a way to detect the completion of the last/longest running transition.
Example:
<style>
.box {
width: 100px;
height: 100px;
transition: width 0.5s, height 6s;
}
.animate {
width: 400px;
height: 400px;
}
</style>
<div class="box"></div>
<script>
// I want to run some code after both the width and height transitions
// are complete
// Listening for transitionend events will fire on every transition
// that ends. So in this case, both width and height. Assume I don't
// know how many properties are being transitioned.
$('.box').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function(ev) {
// ...
});
$('.box').addClass('animate');
</script>
You could find out the number of transitions and then count them down.
var box = document.getElementsByClassName('box')[0];
numTransitions = getComputedStyle(box).transition.split(',').length;
Kind of fragile if your CSS isn't clean, but maybe you have control over that
Yes it is possible but a bit tricky. You extract duration (and delay) from the transition properties, and find the one with the highest value. Since transitionEnd has the (transition)propertyName value, now you only have to compare this with the extracted property. Example is here.
(be aware that you have to wait for 6 seconds until something happens)
function getMaxTransitionDuration(el) {
// small helper to extract the values
function extract(str) {
return str
.replace(/[A-Z]/gi, "")
.split(", ")
.map(parseFloat);
};
// get the current style
var style = getComputedStyle(el);
// get all transition properties
var props = style.transitionProperty.split(", ");
// we need delay and duration
var delays = extract(style.transitionDelay);
var durations = extract(style.transitionDuration);
// combinate delay and duration
var totals = durations.map(function(v, i) {
return v + delays[i];
});
// find the property with longest value
var max = totals[0];
var maxIndex = 0;
for (var i = 1; i < totals.length; i++) {
if (totals[i] > max) {
maxIndex = i;
max = totals[i];
}
}
// and return this property
return props[maxIndex];
}
$('.box').on('transitionend', function(ev) {
var lastProp = getMaxTransitionDuration(this);
if (ev.originalEvent.propertyName == lastProp) {
// here we are.....
}
});
$('.box').addClass('animate');

google places library without map

I am trying to use the google places library for a nearby search request:
https://developers.google.com/maps/documentation/javascript/places#place_search_requests
i just want to pull the json response and put it in a html list, i do now want to show results on a map or something else. I do not want to use map at all. But in documentation it states that there has to be a map
service = new google.maps.places.PlacesService(**map**);
in order to pass it as an argument in the PlacesService function. What i do now is adding a map with height:0 but it still consumes much amount of memory (i develop a sencha touch 2 app and memory is important). Is there any workaround of using nearby search requests without a map? I do not want to use the Google Places API as it does not support JSONP requests.
As documented the PlacesService accepts as argument either a map or an node where to render the attributions for the results.
So you only have to use the node (a node being an html element) instead of the map.
Please note: hiding the attributions violates the places-policies(also hiding the map when used as argument, because the map will show the attributions)
This also may be interesting to you: Google places API does this violate the TOC?
Example: in a nutshell
If you're using jQuery:
var service = new google.maps.places.PlacesService($('#tag-id').get(0));
If plain Javascript:
var service = new google.maps.places.PlacesService(document.createElement('div'));
Then carry on as usual with the rest of the example code:
service.nearbySearch(request, callback);
Example: using details returned
Live demo of this example on jsFiddle.
Note: This example uses jQuery.
<ul class="reviews__content" id="reviews__content">
</ul>
<div id="service-helper"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY_HERE&libraries=places&callback=getRelevantGoogleReviews">
</script>
<script type="text/javascript">
window.getRelevantGoogleReviews = function(){
var service = new google.maps.places.PlacesService($('#service-helper').get(0)); // note that it removes the content inside div with tag '#service-helper'
service.getDetails({
placeId: 'ChIJAwEf5VFQqEcRollj8j_kqnE' // get a placeId using https://developers.google.com/places/web-service/place-id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var resultcontent = '';
for (i=0; i<place.reviews.length; ++i) {
//window.alert('Name:' + place.name + '. ID: ' + place.place_id + '. address: ' + place.formatted_address);
resultcontent += '<li class="reviews__item">'
resultcontent += '<div class="reviews__review-er">' + place.reviews[i].author_name + '</div>';
var reviewDate = new Date(place.reviews[i].time * 1000);
var reviewDateMM = reviewDate.getMonth() + 1;
var reviewDateFormatted = reviewDate.getDate() + '/' + reviewDateMM + '/' + reviewDate.getFullYear();
resultcontent += '<div class="reviews__review-date">' + reviewDateFormatted + '</div>';
resultcontent += '<div class="reviews__review-rating reviews__review-rating--' + place.reviews[i].rating +'"></div>';
if (!!place.reviews[i].text){
resultcontent += '<div class="reviews__review-comment">' + place.reviews[i].text + '</div>';
}
resultcontent += '</li>'
}
$('#reviews__content').append(resultcontent);
}
});
}
</script>
If you want to get location data from a place_id you can do it using the Geocoder class:Here the documentation. With this class you can pass a place_id to the method geocode() and get coordinates and other location data.
Was making a custom address autocomplete for a sign up form.
import {useState, useRef, useEffect } from 'React'
function AutoCompleteInput(){
const [predictions, setPredictions] = useState([]);
const [input, setInput] = useState('');
const [selectedPlaceDetail, addSelectedPlaceDetail] = useState({})
const predictionsRef = useRef();
useEffect(
()=>{
try {
autocompleteService.current.getPlacePredictions({ input }, predictions => {
setPredictions(predictions);
});
} catch (err) {
// do something
}
}
}, [input])
const handleAutoCompletePlaceSelected = placeId=>{
if (window.google) {
const PlacesService = new window.google.maps.places.PlacesService(predictionsRef.current);
try {
PlacesService.getDetails(
{
placeId,
fields: ['address_components'],
},
place => addSelectedPlaceDetail(place)
);
} catch (e) {
console.error(e);
}
}
}
return (
<>
<input onChange={(e)=>setInput(e.currentTarget.value)}
<div ref={predictionsRef}
{ predictions.map(prediction => <div onClick={ ()=>handleAutoCompletePlaceSelected(suggestion.place_id)}> prediction.description </div> )
}
</div>
<>
)
}
So basically, you setup the autocomplete call, and get back the predictions results in your local state.
from there, map and show the results with a click handler that will do the follow up request to the places services with access to the getDetails method for the full address object or whatever fields you want.
you then save that response to your local state and off you go.
Just seen Man asking in a comment above How to initialise the places service without initialising a map? so I thought I would add it here.
placesService = new google.maps.places.PlacesService($('#predicted-places').get(0));
You will need to create an html element with that id first though.
I have come across the same problem.
Why use Maps javascript Api when Places Api is already enabled.Is it an additional price to pay for this simple task?
Maps Javascript API is not used in this code.All the google.maps.Map API methods are taken out. It works fine on jsfiddle.
Just checkout whether it works on local PC.Most of the time it gives the 403 error when i tried running it on local PC storage and using limited requests provided by google API console.
acquire an API key from the google developer console and insert it in the YOUR_API_KEY slot at the script tag of the code
Don't try to run the code here.obviously.The API key needs to be replaced.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var input = document.getElementById('pac-input');
var options = {
types: ['establishment']
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address', 'formatted_phone_number', 'opening_hours', 'website', 'photos']);
autocomplete.addListener('place_changed', placechange);
function placechange() {
var place = autocomplete.getPlace();
var photos = place.photos;
document.getElementById('place_name').textContent = place.name;
document.getElementById('place_id').textContent = place.place_id;
document.getElementById('place_address').textContent = place.formatted_address;
document.getElementById('phone_no').textContent = place.formatted_phone_number;
document.getElementById('open_time').textContent = place.opening_hours.weekday_text[0];
document.getElementById('open_now').textContent = place.opening_hours.open_now;
document.getElementById('photo').src = photos[0].getUrl();
document.getElementById('photo').style = "width:50%;";
document.getElementById('website').textContent = place.website;
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
background-color: #fff;
border-radius: 2px;
border: 1px solid transparent;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
box-sizing: border-box;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
height: 29px;
margin-left: 5px;
margin-top: 10px;
margin-bottom: 10px;
outline: none;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
.controls:focus {
border-color: #4d90fe;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
<div>
<input id="pac-input" class="controls" type="text" placeholder="Enter a business">
</div>
<div id="info-table">
Name: <span id="place_name"></span><br> Place id: <span id="place_id"></span><br> Address :<span id="place_address"></span><br> Phone : <span id="phone_no"></span><br> Openhours: <span id="open_time"></span><br> Open Now : <span id="open_now"></span><br> website : <span id="website"></span><br> photo :<br> <img id="photo" src="" style="display:none;" />
</div>
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
<strong>Place ID:</strong> <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>

How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

I'd like to be able to highlight the drop area as soon as the cursor carrying a file enters the browser window, exactly the way Gmail does it. But I can't make it work, and I feel like I'm just missing something really obvious.
I keep trying to do something like this:
this.body = $('body').get(0)
this.body.addEventListener("dragenter", this.dragenter, true)
this.body.addEventListener("dragleave", this.dragleave, true)`
But that fires the events whenever the cursor moves over and out of elements other than BODY, which makes sense, but absolutely doesn't work. I could place an element on top of everything, covering the entire window and detect on that, but that'd be a horrible way to go about it.
What am I missing?
I solved it with a timeout (not squeaky-clean, but works):
var dropTarget = $('.dropTarget'),
html = $('html'),
showDrag = false,
timeout = -1;
html.bind('dragenter', function () {
dropTarget.addClass('dragging');
showDrag = true;
});
html.bind('dragover', function(){
showDrag = true;
});
html.bind('dragleave', function (e) {
showDrag = false;
clearTimeout( timeout );
timeout = setTimeout( function(){
if( !showDrag ){ dropTarget.removeClass('dragging'); }
}, 200 );
});
My example uses jQuery, but it's not necessary. Here's a summary of what's going on:
Set a flag (showDrag) to true on dragenter and dragover of the html (or body) element.
On dragleave set the flag to false. Then set a brief timeout to check if the flag is still false.
Ideally, keep track of the timeout and clear it before setting the next one.
This way, each dragleave event gives the DOM enough time for a new dragover event to reset the flag. The real, final dragleave that we care about will see that the flag is still false.
Modified version from Rehmat (thx)
I liked this idea and instead of writing a new answer, I am updating it here itself. It can be made more precise by checking window dimensions.
var body = document.querySelector("body");
body.ondragleave = (e) => {
if (
e.clientX >= 0 && e.clientX <= body.clientWidth
&& e.clientY >= 0 && e.clientY <= body.clientHeight
) {} else {
// do something here
}
}
Old Version
Don't know it this works for all cases but in my case it worked very well
$('body').bind("dragleave", function(e) {
if (!e.originalEvent.clientX && !e.originalEvent.clientY) {
//outside body / window
}
});
Adding the events to document seemed to work? Tested with Chrome, Firefox, IE 10.
The first element that gets the event is <html>, which should be ok I think.
var dragCount = 0,
dropzone = document.getElementById('dropzone');
function dragenterDragleave(e) {
e.preventDefault();
dragCount += (e.type === "dragenter" ? 1 : -1);
if (dragCount === 1) {
dropzone.classList.add('drag-highlight');
} else if (dragCount === 0) {
dropzone.classList.remove('drag-highlight');
}
};
document.addEventListener("dragenter", dragenterDragleave);
document.addEventListener("dragleave", dragenterDragleave);
Here's another solution. I wrote it in React, but I'll explain it at the end if you want to rebuild it in plain JS. It's similar to other answers here, but perhaps slightly more refined.
import React from 'react';
import styled from '#emotion/styled';
import BodyEnd from "./BodyEnd";
const DropTarget = styled.div`
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
pointer-events: none;
background-color:rgba(0,0,0,.5);
`;
function addEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions) {
document.addEventListener(type, listener, options);
return () => document.removeEventListener(type, listener, options);
}
function setImmediate(callback: (...args: any[]) => void, ...args: any[]) {
let cancelled = false;
Promise.resolve().then(() => cancelled || callback(...args));
return () => {
cancelled = true;
};
}
function noop(){}
function handleDragOver(ev: DragEvent) {
ev.preventDefault();
ev.dataTransfer!.dropEffect = 'copy';
}
export default class FileDrop extends React.Component {
private listeners: Array<() => void> = [];
state = {
dragging: false,
}
componentDidMount(): void {
let count = 0;
let cancelImmediate = noop;
this.listeners = [
addEventListener('dragover',handleDragOver),
addEventListener('dragenter',ev => {
ev.preventDefault();
if(count === 0) {
this.setState({dragging: true})
}
++count;
}),
addEventListener('dragleave',ev => {
ev.preventDefault();
cancelImmediate = setImmediate(() => {
--count;
if(count === 0) {
this.setState({dragging: false})
}
})
}),
addEventListener('drop',ev => {
ev.preventDefault();
cancelImmediate();
if(count > 0) {
count = 0;
this.setState({dragging: false})
}
}),
]
}
componentWillUnmount(): void {
this.listeners.forEach(f => f());
}
render() {
return this.state.dragging ? <BodyEnd><DropTarget/></BodyEnd> : null;
}
}
So, as others have observed, the dragleave event fires before the next dragenter fires, which means our counter will momentarily hit 0 as we drag files (or whatever) around the page. To prevent that, I've used setImmediate to push the event to the bottom of JavaScript's event queue.
setImmediate isn't well supported, so I wrote my own version which I like better anyway. I haven't seen anyone else implement it quite like this. I use Promise.resolve().then to move the callback to the next tick. This is faster than setImmediate(..., 0) and simpler than many of the other hacks I've seen.
Then the other "trick" I do is to clear/cancel the leave event callback when you drop a file just in case we had a callback pending -- this will prevent the counter from going into the negatives and messing everything up.
That's it. Seems to work very well in my initial testing. No delays, no flashing of my drop target.
Can get the file count too with ev.dataTransfer.items.length
#tyler's answer is the best! I have upvoted it. After spending so many hours I got that suggestion working exactly as intended.
$(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
});
Your third argument to addEventListener is true, which makes the listener run during capture phase (see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow for a visualization). This means that it will capture the events intended for its descendants - and for the body that means all elements on the page. In your handlers, you'll have to check if the element they're triggered for is the body itself. I'll give you my very dirty way of doing it. If anyone knows a simpler way that actually compares elements, I'd love to see it.
this.dragenter = function() {
if ($('body').not(this).length != 0) return;
... functional code ...
}
This finds the body and removes this from the set of elements found. If the set isn't empty, this wasn't the body, so we don't like this and return. If this is body, the set will be empty and the code executes.
You can try with a simple if (this == $('body').get(0)), but that will probably fail miserably.
I was having trouble with this myself and came up with a usable solution, though I'm not crazy about having to use an overlay.
Add ondragover, ondragleave and ondrop to window
Add ondragenter, ondragleave and ondrop to an overlay and a target element
If drop occurs on the window or overlay, it is ignored, whereas the target handles the drop as desired. The reason we need an overlay is because ondragleave triggers every time an element is hovered, so the overlay prevents that from happening, while the drop zone is given a higher z-index so that the files can be dropped. I am using some code snippets found in other drag and drop related questions, so I cannot take full credit. Here's the full HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop Test</title>
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<style>
#overlay {
display: none;
left: 0;
position: absolute;
top: 0;
z-index: 100;
}
#drop-zone {
background-color: #e0e9f1;
display: none;
font-size: 2em;
padding: 10px 0;
position: relative;
text-align: center;
z-index: 150;
}
#drop-zone.hover {
background-color: #b1c9dd;
}
output {
bottom: 10px;
left: 10px;
position: absolute;
}
</style>
<script>
var windowInitialized = false;
var overlayInitialized = false;
var dropZoneInitialized = false;
function handleFileSelect(e) {
e.preventDefault();
var files = e.dataTransfer.files;
var output = [];
for (var i = 0; i < files.length; i++) {
output.push('<li>',
'<strong>', escape(files[i].name), '</strong> (', files[i].type || 'n/a', ') - ',
files[i].size, ' bytes, last modified: ',
files[i].lastModifiedDate ? files[i].lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
window.onload = function () {
var overlay = document.getElementById('overlay');
var dropZone = document.getElementById('drop-zone');
dropZone.ondragenter = function () {
dropZoneInitialized = true;
dropZone.className = 'hover';
};
dropZone.ondragleave = function () {
dropZoneInitialized = false;
dropZone.className = '';
};
dropZone.ondrop = function (e) {
handleFileSelect(e);
dropZoneInitialized = false;
dropZone.className = '';
};
overlay.style.width = (window.innerWidth || document.body.clientWidth) + 'px';
overlay.style.height = (window.innerHeight || document.body.clientHeight) + 'px';
overlay.ondragenter = function () {
if (overlayInitialized) {
return;
}
overlayInitialized = true;
};
overlay.ondragleave = function () {
if (!dropZoneInitialized) {
dropZone.style.display = 'none';
}
overlayInitialized = false;
};
overlay.ondrop = function (e) {
e.preventDefault();
dropZone.style.display = 'none';
};
window.ondragover = function (e) {
e.preventDefault();
if (windowInitialized) {
return;
}
windowInitialized = true;
overlay.style.display = 'block';
dropZone.style.display = 'block';
};
window.ondragleave = function () {
if (!overlayInitialized && !dropZoneInitialized) {
windowInitialized = false;
overlay.style.display = 'none';
dropZone.style.display = 'none';
}
};
window.ondrop = function (e) {
e.preventDefault();
windowInitialized = false;
overlayInitialized = false;
dropZoneInitialized = false;
overlay.style.display = 'none';
dropZone.style.display = 'none';
};
};
</script>
</head>
<body>
<div id="overlay"></div>
<div id="drop-zone">Drop files here</div>
<output id="list"><output>
</body>
</html>
I see a lot of overengineered solutions out there. You should be able to achieve this by simply listening to dragenter and dragleave as your gut seemingly told you.
The tricky part is that when dragleave fires, it seems to have its toElement and fromElement inverted from what makes sense in everyday life (which kind of makes sense in logical terms since it's the inverted action of dragenter).
Bottom-line when you move the cursor from the listening element to outside that element, toElement will have the listening element and fromElement will have the outer non-listening element. In our case, fromElement will be null when we drag outside the browser.
Solution
window.addEventListener("dragleave", function(e){
if (!e.fromElement){
console.log("Dragging back to OS")
}
})
window.addEventListener("dragenter", function(e){
console.log("Dragging to browser")
})
The ondragenter is fired quite often. You can avoid using a helper variable like draggedFile. If you don't care how often your on ondragenter function is being called, you can remove that helper variable.
Solution:
let draggedFile = false;
window.ondragenter = (e) => {
if(!draggedFile) {
draggedFile = true;
console.log("dragenter");
}
}
window.ondragleave = (e) => {
if (!e.fromElement && draggedFile) {
draggedFile = false;
console.log("dragleave");
}
}
Have you noticed that there is a delay before the dropzone disappears in Gmail? My guess is that they have it disappear on a timer (~500ms) that gets reset by dragover or some such event.
The core of the problem you described is that dragleave is triggered even when you drag into a child element. I'm trying to find a way to detect this, but I don't have an elegantly clean solution yet.
really sorry to post something that is angular & underscore specific, however the way i solved the problem (HTML5 spec, works on chrome) should be easy to observe.
.directive('documentDragAndDropTrigger', function(){
return{
controller: function($scope, $document){
$scope.drag_and_drop = {};
function set_document_drag_state(state){
$scope.$apply(function(){
if(state){
$document.context.body.classList.add("drag-over");
$scope.drag_and_drop.external_dragging = true;
}
else{
$document.context.body.classList.remove("drag-over");
$scope.drag_and_drop.external_dragging = false;
}
});
}
var drag_enters = [];
function reset_drag(){
drag_enters = [];
set_document_drag_state(false);
}
function drag_enters_push(event){
var element = event.target;
drag_enters.push(element);
set_document_drag_state(true);
}
function drag_leaves_push(event){
var element = event.target;
var position_in_drag_enter = _.find(drag_enters, _.partial(_.isEqual, element));
if(!_.isUndefined(position_in_drag_enter)){
drag_enters.splice(position_in_drag_enter,1);
}
if(_.isEmpty(drag_enters)){
set_document_drag_state(false);
}
}
$document.bind("dragenter",function(event){
console.log("enter", "doc","drag", event);
drag_enters_push(event);
});
$document.bind("dragleave",function(event){
console.log("leave", "doc", "drag", event);
drag_leaves_push(event);
console.log(drag_enters.length);
});
$document.bind("drop",function(event){
reset_drag();
console.log("drop","doc", "drag",event);
});
}
};
})
I use a list to represent the elements that have triggered a drag enter event. when a drag leave event happens i find the element in the drag enter list that matches, remove it from the list, and if the resulting list is empty i know that i have dragged outside of the document/window.
I need to reset the list containing dragged over elements after a drop event occurs, or the next time I start dragging something the list will be populated with elements from the last drag and drop action.
I have only tested this on chrome so far. I made this because Firefox and chrome have different API implementations of HTML5 DND. (drag and drop).
really hope this helps some people.
When the file enters and leaves child elements it fires additional dragenter and dragleave so you need to count up and down.
var count = 0
document.addEventListener("dragenter", function() {
if (count === 0) {
setActive()
}
count++
})
document.addEventListener("dragleave", function() {
count--
if (count === 0) {
setInactive()
}
})
document.addEventListener("drop", function() {
if (count > 0) {
setInactive()
}
count = 0
})
I found out from looking at the spec that if the evt.dataTransfer.dropEffect on dragEnd match none then it's a cancelation.
I did already use that event to handle copying without affecting the clipboard. so this was good for me.
When I hit Esc then the drop effect was equal to none
window.ondragend = evt => {
if (evt.dataTransfer.dropEffect === 'none') abort
if (evt.dataTransfer.dropEffect === 'copy') copy // user holds alt on mac
if (evt.dataTransfer.dropEffect === 'move') move
}
on "dropend" event you can check the value of the document.focus() was the magic trick in my case.