DOM changes execute out of order in my Angular2 component - dom

I have an Angular2 component that updates an imported HTML file that I am annotating and allowing the user to edit. To do this I am updating the DOM directly using plain HTML5. On click a class is supposed to be added to the clicked DOM element. In the browser (FF and Chrome on linux) it gets added temporarily - meaning that if I print the node immediately I see the class, but after I exit the function and print it I do not. Inspect Element shows that the element is updated to <.... class> with no value when the element is clicked.
This was working when I implemented it without Angular.
I tried direct DOM manipulation (with classList.add and x.className=y), angular's Renderer, and running the code via NgZone, and all had the same effect. Can someone tell me why this is happening and what I can do to fix it?
Note: this is (supposed to be) a simple internal tool - at this point I need a quick fix (though additional advice is welcome as well).
(A few irrelevant parts of the code that are not fully implemented yet were omitted here.)
import { Component, OnInit, NgZone } from "#angular/core";
import { Http, Headers, RequestOptions } from "#angular/http";
#Component({
selector: "editor",
templateUrl: `editor/starterDemo.html`
})
export class EditorComponent implements OnInit {
ngOnInit() {
this.fixImagePaths();
this.annotate();
}
constructor(public http: Http, public zone: NgZone) { }
// constructor(public http: Http, public renderer: Renderer) { }
fixImagePaths = () => {
const els = document.querySelectorAll('img');
for (let i: number = 0, el: any; (el = els[i]); i++) {
el.src = 'editor/' + el.getAttribute('src');
}
}
annotate = () => {
document.body.addEventListener('dragover', this.drag_over);
document.body.addEventListener('click', this.selectNone);
document.body.addEventListener('keydown', this.keyDown);
const els = document.querySelectorAll('img, .box');
for (let i: number = 0, el: any; (el = els[i]); i++) {
el.draggable = true;
el.addEventListener('dragstart', this.drag_start);
el.addEventListener('click', this.selectItem);
}
}
selectItem = (event) => {
console.log("select item!");
this.selectNone();
// this.zone.run(() => {
event.target.closest('[draggable]').classList.add('dragme');
// });
// this.renderer.setElementClass(event.target.closest('[draggable]').nativeElement, 'dragme', true);
// console.log(event.target.closest('[draggable]'));
// console.log(event.target.closest('[draggable]').classList);
// console.log(event.target.closest('[draggable]').classList.contains('dragme'));
console.log(this.selected());
return false;
}
selectNone = () => {
this.selected() && this.selected().classList.remove('dragme');
}
selected = (): any => document.getElementsByClassName('dragme')[0];
}
HTML:
<div class='box'
style="background-color: white; position: absolute; top: 847px; left: 842px; z-index: 20; height: 118px; width: 351px"></div>
<img src="Screenshot1.png"
style="position: absolute; top: 0px; left: -1px" />
<img src="Screenshot2.png"
style="position: absolute; top: 913px; left: 0px; z-index: 2"/>
<img src="Screenshot3.png"
style="position: absolute; top: 1768px; left: 0px" />
<div style="height: 2000px"> </div>

I just figured out the problem (after hours of anguish). It seems that on linux chrome, return false is not good enough to prevent event propagation, and so the click event was running twice, once before and once after the addClass call. Since the click event has a selectNone() in the beginning (to clear the existing selected item), it ran selectNone() before and after adding the class. I added event.preventDefault(); and event.stopPropagation(); to my event handlers.
I hope this helps someone.

Related

StencilJS component with shadow dom enabled does not generate the helper CSS classes for dynamically added elements on IE11/Edge

I've created a new project using the stencil component starter. Inside my component I'm using an external JS nouislider, which injects HTML elements into my div (this.slider ref):
...
componentDidLoad() {
noUiSlider.create(this.slider, {
start: [20, 80],
range: {
'min': 0,
'max': 100
}
})
}
...
I've copied the slider's CSS into my-component.css and rewrote everything with :host selectors for the shadow dom:
:host(.my-component) .noUi-target {
position: relative;
direction: ltr
}
Everything works fine on Chrome/Firefox but the slider styles are not working on IE11/Edge because Stencil appends a helper sc-my-component class to every element that I have inside the render method and generates CSS rules like so:
.my-component.sc-my-component-h .noUi-target.sc-my-component {
position: relative;
direction: ltr
}
but the injected nouislider child HTML elements don't have the helper classes on them. I have an ugly fix for this case atm:
...
componentDidLoad() {
noUiSlider.create(this.slider, {
start: [20, 80],
range: {
'min': 0,
'max': 100
}
})
this.slider.querySelectorAll('div').forEach((child)=>{
child.classList.add('sc-my-component')
})
}
...
I'm appending the helper classes after the slider is created (the slider generates child divs only). Is there a better way to tell Stencil that I'm injecting elements inside lifecycle methods and that it needs to recognize those elements when CSS rules are being generated?
This is not an answer to your question, nevertheless this could also be interesting for you:
We are currently working on the same topic (StencilJS, shadow: true, noUiSlider) and encountered the problem, that the slider's touch events are not working correctly in shadowDOM on mobile devices. We found a solution for this and already created a PR (https://github.com/leongersen/noUiSlider/pull/1060).
I too had problems using nouislider in StencilJS but just managed to make it work.
my-slider.scss
#import '~nouislider/distribute/nouislider.css';
:host {
padding: 50px 30px;
display: block;
}
my-slider.tsx
import { Component, h, Prop, Event, EventEmitter } from '#stencil/core';
import noUiSlider from "nouislider";
#Component({
tag: 'skim-slider',
styleUrl: 'skim-slider.scss',
shadow: true
})
export class SkimSlider {
#Prop() min!: number;
#Prop() max!: number;
private slider: HTMLElement;
#Event() update: EventEmitter;
componentDidLoad() {
const slider = noUiSlider.create(this.slider, {
start: [this.min, this.max],
tooltips: [true, true],
range: {
'min': this.min,
'max': this.max
}
});
slider.on('change', (value) => this.update.emit(value));
}
render() {
return (
<div ref={e => this.slider = e}></div>
);
}
}
The trick that did it for me was 'display: block'

Resetting forms in Polymer 2.x

I am trying to reset my form. What am I doing wrong? What is best-practice?
Here is my Plunk demo.
My problem on the demo is that connectedCallback() appears to fire continually (not just on initial load), thereby losing the value of savedItem by updating it to newItem on each update.
Here is the same issue on Github.
https://plnkr.co/edit/wRdXXws2UXl3VXrycqua?p=preview
my-demo.html
<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer-element.html">
<link rel="import" href="paper-toggle-button/paper-toggle-button.html">
<dom-module id="my-demo">
<template>
<style>
:host > * {
margin-top: 40px;
font-size: 18px;
}
button.save {
color: white;
background-color: blue;
}
</style>
<paper-toggle-button checked="{{item.alice}}">Alice</paper-toggle-button>
<paper-toggle-button checked="{{item.bob}}">Bob</paper-toggle-button>
<paper-toggle-button checked="{{item.charlie}}">Charlie</paper-toggle-button>
<paper-toggle-button checked="{{item.dave}}">Dave</paper-toggle-button>
<button>Reset</button>
<button class="save" on-tap="_reset">Save</button>
</template>
<script>
class MyDemo extends Polymer.Element {
static get is() {
return 'my-demo';
}
static get properties() {
return {
item: {
type: Object,
notify: true,
value: () => {
return {
alice: false,
bob: false,
charlie: false,
dave: true,
};
},
},
savedItem: {
type: Object,
notify: true,
},
};
}
connectedCallback() {
super.connectedCallback();
this.set('savedItem', this.item);
}
static get observers() {
return [
'_itemChanged(item.*)',
];
}
_itemChanged(newItem) {
console.log('saved-item', this.savedItem);
console.log('new-item', newItem);
}
_reset() {
this.set('item', this.savedItem);
}
}
window.customElements.define(MyDemo.is, MyDemo);
</script>
</dom-module>
Edit
Steps to recreate the problem
Open the demo here.
Open your console.
Navigate in the Plunker to my-demo.html
Click one of the toggle switches.
Notice in the console, the savedItem property updates to the current item property.
Notice, this appears to be the result of the following code block.
connectedCallback() {
super.connectedCallback();
this.set('savedItem', this.item);
}
But how can this be? Because I thought connectedCallback() only fired once at initialization time?
tldr; The connectedCallback() isn't actually being called more than once in this case. savedItem and item are always the same object in your code because JavaScript passes objects by reference.
Object references
In the following:
connectedCallback() {
this.set('savedItem', this.item);
}
_reset() {
this.set('item', this.savedItem);
}
savedItem and item are both references to the same object. Calling this.set() does not automatically clone the operand (nor does the = operator).
One solution is to clone the object before assignment (using ES2017 object-spread operator):
connectedCallback() {
this.savedItem = {...this.item};
}
_reset() {
this.item = {...this.savedItem};
}
updated plunker
Best practice (or simpler reset method)
A simpler way to reset the form is to let iron-form handle the form's reset event, where it resets the form's named inputs to their initial values. This saves you from having to declare savedItem and no extra JavaScript to manage it.
To accomplish this, wrap the <paper-toggle-button>'s in an <iron-form>, and add name attributes to them. Then, insert an <input type="reset"> in the form, which serves as the reset button.
<iron-form>
<form>
<paper-toggle-button name="alice" checked="{{item.alice}}">Alice</paper-toggle-button>
<paper-toggle-button name="bob" checked="{{item.bob}}">Bob</paper-toggle-button>
<paper-toggle-button name="charlie" checked="{{item.charlie}}">Charlie</paper-toggle-button>
<paper-toggle-button name="dave" checked="{{item.dave}}">Dave</paper-toggle-button>
<input type="reset" class="save">
</form>
</iron-form>
demo

Leaflet.js: Use ctrl + scroll to zoom the map & Move map with two fingers on mobile

I'm using http://leafletjs.com/ ... is it possible to only:
Use ctrl + scroll to zoom the map
Move map with two fingers on mobile/tablet
... so similar what google maps does? With the comments ...
So far thats my setup:
// Leaflet Maps
var contactmap = L.map('contact-map', {
center: [41.3947688, 2.0787279],
zoom: 15,
scrollWheelZoom: false
});
There is an amazing library that does exactly that. Leaflet.GestureHandling
It is an add on to leaflet that works right of the box, it's also modular and can be installed using npm.
Here's a working example using leaflet and GestureHandling.
You can try it also on mobile.
P.S. It has multiple languages baked in:)
// Attach it as a handler to the map
const map = L.map('map', {
gestureHandling: true
}).setView([51.505, -0.09], 13);
// Add tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
#map {
height: 400px;
width: 400px;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.4.0/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
<link rel="stylesheet" href="//unpkg.com/leaflet-gesture-handling/dist/leaflet-gesture-handling.min.css"
type="text/css">
<script src="https://unpkg.com/leaflet#1.4.0/dist/leaflet.js"
integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
crossorigin=""></script>
<script src="//unpkg.com/leaflet-gesture-handling"></script>
<div id="map"></div>
zoom map using ctrl + zoom. I did in custom way .
html code is below
<div id="map"></div>
css
.map-scroll:before {
content: 'Use ctrl + scroll to zoom the map';
position: absolute;
top: 50%;
left: 50%;
z-index: 999;
font-size: 34px;
}
.map-scroll:after {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
content: '';
background: #00000061;
z-index: 999;
}
jQuery
//disable default scroll
map.scrollWheelZoom.disable();
$("#map").bind('mousewheel DOMMouseScroll', function (event) {
event.stopPropagation();
if (event.ctrlKey == true) {
event.preventDefault();
map.scrollWheelZoom.enable();
$('#map').removeClass('map-scroll');
setTimeout(function(){
map.scrollWheelZoom.disable();
}, 1000);
} else {
map.scrollWheelZoom.disable();
$('#map').addClass('map-scroll');
}
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
$('#map').removeClass('map-scroll');
})
In simple way when user scroll on map then detect ctrl button is pressed or not then just I add one class that will showing message on map. and prevent screen zoom-in and zoom-out outside of map.
I managed to solve your second problem.
I used css for displaying the message using a ::after pseudo selector.
#map {
&.swiping::after {
content: 'Use two fingers to move the map';
}
}
And javascript to capture the touch events.
mapEl.addEventListener("touchstart", onTwoFingerDrag);
mapEl.addEventListener("touchend", onTwoFingerDrag);
function onTwoFingerDrag (e) {
if (e.type === 'touchstart' && e.touches.length === 1) {
e.currentTarget.classList.add('swiping')
} else {
e.currentTarget.classList.remove('swiping')
}
}
It checks if the type is a touchevent and if you are using 1 finger, if so it adds the class to the map with the message. If you use more than one finger it removes the class.
Working demo I suggest you using a mobile device.
Code pen from the demo

Can you use jQuery .css() with .live()?

I have a div with class="centerMessage" . This div is inserted into the DOM at a point after the page is loaded. I would like to change the CSS on this div to center it. I tried the CSS function below, but it did not work. Does anybody know a way to do this?
function centerPopup() {
var winWidth = $(window).width();
var winHeight = $(window).height();
var positionLeft = (winWidth/2) - (($('.centerMessage').width())/2);
var positionTop = (winHeight/2) - (($('.centerMessage').height())/2);
$('.centerMessage').live( function(){
$(this).css("position","absolute");
$(this).css("top",positionTop + "px");
$(this).css("left",positionLeft + "px");
});
}
If my assumption of what you're trying to achieve is correct, you don't need any Javascript to do this. It can be achieved by some simple CSS.
.centerMessage {
position: absolute;
top: 50%;
left: 50%;
margin-top: -150px; /* half of the height */
margin-left: -300px; /* half of the width */
width: 600px;
height: 300px;
background: #ccc;
}
Demo: http://jsbin.com/awuja4
.live() does not accept JUST a function. If you want something to happen with live, it needs an event as well, like click. If you want something to happen always for every .centerMessage, you will need the plugin .livequery()
I believe that the following works in FF & Webkit.
div.centerMessage{
position: absolute;
width: /* width */;
height: /* height */;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
margin: auto;
}
I know this is already answered, but I thought I'd provide a working jsFiddle demo using JavaScript like the OP originally wanted, but instead of using live(), I use setInterval():
First, we need to declare a couple variables for use later:
var $centerMessage,
intervalId;
The OP's issue was that they didn't know when the div was going to be created, so with that in mind we create a function to do just that and call it via setTimeout() to simulate this div creation:
function createDiv() {
$('<div class="centerMessage">Center Message Div</div>').appendTo("body");
}
$(function() { setTimeout("createDiv()", 5000); });
Finally, we need to create a function that will check, using setInterval() at a rate of 100ms, to see if the div has been created and upon creation, goes about modifying the div via jQuery:
function checkForDiv() {
$centerMessage = $('.centerMessage');
if ($centerMessage.length) {
clearInterval(intervalId);
var $window = $(window),
winHeight = $window.height(),
winWidth = $window.width(),
positionTop = (winHeight / 2) - ($centerMessage.height() / 2),
positionLeft = (winWidth / 2) - ($centerMessage.width() / 2);
$centerMessage.css({
"display" : "block",
"position" : "absolute",
"top" : positionTop.toString() + "px",
"left" : positionLeft.toString() + "px"
});
}
}
$(function() { intervalId = setInterval(checkForDiv, 100); });
Try Use this
$('.centerMessage').live('click', function(){
Try this
$('#foo').on('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
OR
$('#foo').live('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');

jquery ui connected sortables: cancel, disable, destroy... nada

I have two connected sortable lists.
For the sake of my question, when I start dragging an item from #sortable1 to #sortable2, in the start event I want to cancel/ disable/ the drop in #sortable2
Nothing works?
$("#sortable1, #sortable2").sortable({
connectWith: "#sortable1, #sortable2",
start: startDrag
});
function startDrag(event, ui) {
$("#sortable2").css("opacity","0.5");
// $("#sortable2").sortable("cancel"); // goes whooooo
/* docs say:
If the sortable item is being moved from one connected sortable to another:
$(ui.sender).sortable('cancel');
will cancel the change. Useful in the 'receive' callback.
*/
// $("#sortable1").sortable("cancel"); // I only want to cancel dropping in sortable2...
// $("#sortable2").sortable("disable"); // disables only after the drop event
// $("#sortable2").sortable("destroy"); // same as "disable"
}
function stopDrag(event, ui) {
$("#sortable2").css("opacity","1.0");
// $("#sortable2").sortable("enable");
}
My JSFiddle here: http://jsfiddle.net/tunafish/m32XW/
I have found 2 more questions like mine:
jQuery sortable('disable') from start event not entirely working like expected
http://forum.jquery.com/topic/disable-a-sortable-while-dragging-with-connectedlists
No responses..
Anything appreciated!
EDIT: I also tried to overlay a div like a modal on the sortable, but can still be dragged to that way. The only thing that worked is a show/hide, but that's not an option for me.
OK here is my app; two lists of images, sortable and you can copy over from the connected list.
If an item already exists in the target it's disabled.
Hopefully useful to someone...
JSFiffle here: http://jsfiddle.net/tunafish/VBG5V/
CSS:
.page { width: 410px; padding: 20px; margin: 0 auto; background: darkgray; }
.album { list-style: none; overflow: hidden;
width: 410px; margin: 0; padding: 0; padding-top: 5px;
background: gray;
}
.listing { margin-bottom: 10px; }
.album li { float: left; outline: none;
width: 120px; height: 80px; margin: 0 0 5px 5px; padding: 5px;
background: #222222;
}
li.placeholder { background: lightgray; }
JS:
$("ul, li").disableSelection();
$(".album, .favorites").sortable({
connectWith: ".album, .favorites",
placeholder: "placeholder",
forcePlaceholderSize: true,
revert: 300,
helper: "clone",
stop: uiStop,
receive: uiReceive,
over: uiOver
});
$(".album li").mousedown(mStart);
var iSender, iTarget, iIndex, iId, iSrc, iCopy;
var overCount = 0;
/* everything starts here */
function mStart() {
// remove any remaining .copy classes
$(iSender + " li").removeClass("copy");
// set vars
if ($(this).parent().hasClass("listing")) { iSender = ".listing"; iTarget = ".favorites"; }
else { iSender = ".favorites"; iTarget = ".listing"; }
iIndex = $(this).index();
iId = $(this).attr("id");
iSrc = $(this).find("img").attr("src");
iCopy = $(iTarget + " li img[src*='" + iSrc + "']").length > 0; // boolean, true if there is allready a copy in the target list
// disable target if item is allready in there
if (iCopy) { $(iTarget).css("opacity","0.5").sortable("disable"); }
}
/* when sorting has stopped */
function uiStop(event, ui) {
// enable target
$(iTarget).css("opacity","1.0").sortable("enable");
// reset item vars
iSender = iTarget = iIndex = iId = iSrc = iCopy = undefined;
overCount = 0;
// reinit mousedown, live() did not work to disable
$(".album li").mousedown(mStart);
}
/* rolling over the receiver - over, out, over etc. */
function uiOver(event, ui) {
// only if item in not allready in the target
if (!iCopy) {
// counter for over/out (numbers even/uneven)
overCount++;
// if even [over], clone to original index in sender, show and fadein (sortables hides it)
if (overCount%2) {
if (iIndex == 0) { ui.item.clone().addClass("copy").attr("id", iId).prependTo(iSender).fadeIn("slow"); }
else { ui.item.clone().addClass("copy").attr("id", iId).insertAfter(iSender + " li:eq(" + iIndex + ")").fadeIn("slow"); }
}
// else uneven [out], remove copies
else { $(iSender + " li.copy").remove(); }
}
// else whoooooo
}
/* list transfers, fix ID's here */
function uiReceive(event, ui) {
(iTarget == ".favorites") ? liPrefix = "fli-" : liPrefix = "lli-";
// set ID with index for each matched element
$(iTarget + " li").each(function(index) {
$(this).attr("id", liPrefix + (index + 1)); // id's start from 1
});
}
HTML:
<div class="page">
<div class="container">
<h2>Photo Album</h2>
<ul class="listing album">
<li id="li-1"><img src="tn/001.jpg" /></li>
<li id="li-2"><img src="tn/002.jpg" /></li>
<li id="li-3"><img src="tn/003.jpg" /></li>
<li id="li-4"><img src="tn/004.jpg" /></li>
<li id="li-5"><img src="tn/005.jpg" /></li>
</ul>
</div>
<div style="clear:both;"></div>
<div class="container">
<h2>Favorites</h2>
<ul class="favorites album">
<li id="fli-1"><img src="tn/001.jpg" /></li>
<li id="fli-2"><img src="tn/002.jpg" /></li>
<li id="fli-3"><img src="tn/010.jpg" /></li>
</ul>
</div>
</div>
/* docs say:
If the sortable item is being moved from one connected sortable to another:
$(ui.sender).sortable('cancel');
will cancel the change. Useful in the 'receive' callback.
*/
This code was what I spent 30 minutes looking for!
Ok I found some sort of hack for this.
When an item is moved from #sortable1 to #sortable2, when dragged over #sortable2 there is a list item added with class .placeholder
So in UI's over event I did
$("#sortable2 li.placeholder").hide();
Than set it back with UI's stop event
$("#sortable2 li.placeholder").show();
This is only for visuals though.. The item is still moved into #sortable2 so you need to remove() it there. To mimic copying you need to add a clone() back in #sortable2. You can get it's original index() in UI's start event and than use insertAfter(id - 1)
At the moment I can only clone in UI's receive event, I would prefer in UI's over but can't get it to work..