AddEventListener only works with the last picture - addeventlistener

I have one problem. addEventListener only works with the last element of the loop. I know what is the problem, but I can't figure it out. I get the JSON object from another function with the information. Later on the left side there should be clickable pictures. After clicking it I should get the same picture on the right side showed. Still it works only with the last one.
function myFunction(obj) {
var listItems = document.getElementsByClassName("newimg");
for (var i = 0; i < obj.length; i++) {
(function (i) {
document.getElementById("imgSmall").innerHTML += `<br></br><img id="${i}" class="newimg" src=${obj[i].download_url} >`;
let p = obj[i];
listItems[i].addEventListener('click', function() { makeithappen(p);},true);
}(i));
//obj[i].width,obj[i].height,obj[i].author,obj[i].download_url>
}
}
function makeithappen(k) {
document.getElementById("imgLarge").innerHTML = `<br class="text"> AUTHOR: ${k.author}, WIDTH: ${k.width}, HEIGHT: ${k.height}</br><img class="img2" src=${k.download_url} >`;
}

For quick fix.
Replace in your code
listItems[i].addEventListener('click', function() { makeithappen(p);},true);
with
listItems[i].onload = function() {
listItems[i].addEventListener('click', function () { makeithappen(p); }, true);
}

So when you got your listItems you weren't finished with the creation of more images. So new image means new list.
for (let i = 0; i < obj.length; i++) {
document.getElementById("imgSmall").innerHTML += `<br></br><img id="${i}" class="newimg" src=${obj[i].download_url}>`;
const listItems = document.getElementsByClassName("newimg");
listItems[i].addEventListener('click', function () { makeithappen(p); }, true);
}
function makeithappen(k) {
document.getElementById("imgLarge").innerHTML = `<br class="text"> AUTHOR: ${k.author}, WIDTH: ${k.width}, HEIGHT: ${k.height}</br><img class="img2" src=${k.download_url} >`;
}
Pleas do refactor <br></br> into something with css, margin or padding or whatever. This will then allow you to create the images with let div = document.createElement('img') and bind the event listener directly div.addEventlistener(...)

Related

Drag and Drop limitation in Konva js

I recently began to learn Konva-JS... please help me :)
<script>
var width = window.innerWidth;
var height = window.innerHeight;
function loadImages(sources, callback) {
var assetDir = '/assets/';
var images = {};
var loadedImages = 0;
var numImages = 0;
for(var src in sources) {
numImages++;
}
for(var src in sources) {
images[src] = new Image();
images[src].onload = function() {
if(++loadedImages >= numImages) {
callback(images);
}
};
images[src].src = assetDir + sources[src];
}
}
function isNearOutline(animal, outline) {
var a = animal;
var o = outline;
var ax = a.getX();
var ay = a.getY();
if(ax > o.x - 20 && ax < o.x + 20 && ay > o.y - 20 && ay < o.y + 20) {
return true;
}
else {
return false;
}
}
function drawBackground(background, beachImg, text) {
var context = background.getContext();
context.drawImage(beachImg, 0, 0);
context.setAttr('font', '20pt Calibri');
context.setAttr('textAlign', 'center');
context.setAttr('fillStyle', 'white');
context.fillText(text, background.getStage().getWidth() / 2, 40);
}
function initStage(images) {
var stage = new Konva.Stage({
container: 'container',
width: 578,
height: 530
});
var background = new Konva.Layer();
var animalLayer = new Konva.Layer();
var animalShapes = [];
var score = 0;
// image positions
var animals = {
snake: {
x: 10,
y: 70
},
giraffe: {
x: 90,
y: 70
},
monkey: {
x: 275,
y: 70
},
lion: {
x: 400,
y: 70
}
};
var outlines = {
snake_black: {
x: 275,
y: 350
},
giraffe_black: {
x: 390,
y: 250
},
monkey_black: {
x: 300,
y: 420
},
lion_black: {
x: 100,
y: 390
}
};
// create draggable animals
for(var key in animals) {
// anonymous function to induce scope
(function() {
var privKey = key;
var anim = animals[key];
var animal = new Konva.Image({
image: images[key],
x: anim.x,
y: anim.y,
draggable: true
});
animal.on('dragstart', function() {
this.moveToTop();
animalLayer.draw();
});
/*
* check if animal is in the right spot and
* snap into place if it is
*/
animal.on('dragend', function() {
var outline = outlines[privKey + '_black'];
if(!animal.inRightPlace && isNearOutline(animal, outline)) {
animal.position({
x : outline.x,
y : outline.y
});
animalLayer.draw();
animal.inRightPlace = true;
if(++score >= 4) {
var text = 'You win! Enjoy your booty!';
drawBackground(background, images.beach, text);
}
// disable drag and drop
setTimeout(function() {
animal.draggable(false);
}, 50);
}
});
// make animal glow on mouseover
animal.on('mouseover', function() {
animal.image(images[privKey + '_glow']);
animalLayer.draw();
document.body.style.cursor = 'pointer';
});
// return animal on mouseout
animal.on('mouseout', function() {
animal.image(images[privKey]);
animalLayer.draw();
document.body.style.cursor = 'default';
});
animal.on('dragmove', function() {
document.body.style.cursor = 'pointer';
});
animalLayer.add(animal);
animalShapes.push(animal);
})();
}
// create animal outlines
for(var key in outlines) {
// anonymous function to induce scope
(function() {
var imageObj = images[key];
var out = outlines[key];
var outline = new Konva.Image({
image: imageObj,
x: out.x,
y: out.y
});
animalLayer.add(outline);
})();
}
stage.add(background);
stage.add(animalLayer);
drawBackground(background, images.beach, 'Ahoy! Put the animals on the beach!');
}
var sources = {
beach: 'beach.png',
snake: 'snake.png',
snake_glow: 'snake-glow.png',
snake_black: 'snake-black.png',
lion: 'lion.png',
lion_glow: 'lion-glow.png',
lion_black: 'lion-black.png',
monkey: 'monkey.png',
monkey_glow: 'monkey-glow.png',
monkey_black: 'monkey-black.png',
giraffe: 'giraffe.png',
giraffe_glow: 'giraffe-glow.png',
giraffe_black: 'giraffe-black.png'
};
loadImages(sources, initStage);
</script>
as we can see in this example Animals_on_the_Beach_Game the animal's images are drag-able and can be drop ever where.... but I want to change it in the way that it just can drop on the specific place ... what can I do ?
thank you :)
This is more of a design question, as letting go of the mouse button isn't something you can prevent. It would also be non-intuitive to keep the image attached to the mouse position as you would then need a new mouse event to associate with dropping it. What I've done for a drag and drop UI was to either (1) destroy the dropped shape, or if that wasn't an option, (2) animate the shape back (i.e. snap back) to its original position. Alternatively, you might (3) find the closest likely valid drop target and snap to that location.
First you define lionOrigin, that maybe you already have.
You have to implement the call on the dragend event of the object dragged, so let's say the lion. You have to check position of the lion in relation to the end desired position, let's call it lionDestiny. That can be done with a simple grometry: calculate the distance between to point. We do that with distanceA2B() function.
Now you can establish an offset inside wich you can snap the object, as it is close enough. If the minimal offset is not achieved, then you place the lion back on lionOrigin.
Al last, in konvajs you can use .x() and .y() to easily get or set position to lion.
Something like this:
var lionOrigin = [50,50];
var lionDestiny = [200,200];
var offset = 20;
distanceA2B(a,b) {
return Math.sqrt( ((a[0]-b[0])*(a[0]-b[0])) + ((a[1]-b[1])*(a[1]-b[1])) );
}
lion.on('dragend', (e) => {
var d = distanceA2B([lion.x(),lion.y()],lionDestiny);
if(d<offset){
lion.x(lionDestiny[0]);
lion.y(lionDestiny[1]);
}else{
lion.x(lionOrigin[0]);
lion.y(lionOrigin[1]);
}
});
Hope this helps!
It would have been better if you could explain your question more when you say you want to move any shape to a specific position. Though konva.js provides you with various events through which you can do this. For example, suppose you want to interchange the location of two shapes when you drag and move the first shape to the second and drop it there. In this case, you can use dragend event of konva. So when you move the target element to another element and drop it there, check if they are intersecting each other or not and then interchange their coordinates with each other.
Here is the function to find the intersection between two elements:
haveIntersection(r1, r2) {
return !(
r2.x > r1.x + r1.width ||
r2.x + r2.width < r1.x ||
r2.y > r1.y + r1.height ||
r2.y + r2.height < r1.y
);
}
And from here, you can try to understand the functionality. Though it's in nuxt.js but the events and scripts would be almost same if you are using only javascript. You can find sample code with an explanation for replacing the location of two shapes with each other. So even if you don't want to replace the locations but you want to move your target element to any position this will make you understand how to do this.

Angular view gets out of sync with model when dragging items from one list to another

I have created a custom directive that allows me to connect multiple sortable lists via drag and drop using angular js and jquery ui. The way it should work is the following:
When drag starts, keep track of the initial position of the item in the array and the value of ng-model for that sortable
When the drag ends, if the item is received to a different list, keep track of the ng-model of that list and the target position of the element
Broadcast an event with that data so that the controller can change the positions of the items from one array to another
The problem is that once I move one item from one list to another, even though the items in the arrays go where they should, in the view some HTML elements disappear.
Here is the sortable directive:
app.directive('mySortable',function(){
return {
link:function(scope,el,attrs){
var options = {};
if(attrs.connectWith)
{
options.connectWith = attrs.connectWith;
}
el.sortable(options);
el.disableSelection();
el.on("sortstart", function(event, ui){
var from_index = angular.element(ui.item).scope()?angular.element(ui.item).scope().$index : 0;
var from_model = angular.element(ui.item.parent()).attr('ng-model');
ui.item.scope().sortableData = {from_index: from_index, from_model: from_model};
});
el.on("sortreceive", function(event, ui){
ui.item.scope().sortableData.to_index = el.children().index(ui.item);
ui.item.scope().sortableData.to_model = angular.element(el).attr('ng-model');
});
el.on( "sortdeactivate", function( event, ui ) {
var to_model = angular.element(el).attr('ng-model');
var from = angular.element(ui.item).scope()?angular.element(ui.item).scope().$index : 0;
var to = el.children().index(ui.item);
if(to>=0){
scope.$apply(function(){
if(from>=0){
scope.$emit('list-sorted', {from:from,to:to}, ui.item.scope());
}else{
scope.$emit('list-appended', {to:to, name:ui.item.text()});
ui.item.remove();
}
})
}
} );
}
}
})
And here is the controller logic that handles it's event:
$scope.$on('list-sorted', function(ev, val, task_scope){
var sd = task_scope.sortableData;
if(sd.to_model)
{
$timeout(function(){
$scope[sd.to_model].splice(sd.to_index, 0, $scope[sd.from_model].splice(sd.from_index, 1)[0]);
});
}
else
{
$timeout(function(){
$scope[sd.from_model].splice(val.to, 0, $scope[sd.from_model].splice(val.from, 1)[0]);
});
}
console.log($scope);
});
What's wrong?
Example JS Fiddle
It seems that the controller logic comports an error.
Is it fine like this:
var sd = item_scope.sortableData;
// If the item is supposed to be dropped to a different list, move it from one list to another
if(sd.to_model)
{
console.log("to a different list", val)
$timeout(function(){
$scope[sd.to_model].splice(val.to, 0, $scope[sd.from_model].splice(sd.from_index, 0));
});
}
else
{
console.log("to the same list")
$timeout(function(){
$scope[sd.from_model].splice(val.to, 0, $scope[sd.from_model].splice(val.from, 1)[0]);
});
}

Titanium WebView.toImage on coverFlowView

A have several views with WebViews on them. I need to make it in a coverFlowView. For that i make my views toImage, to put after on the coverFlow, but the issue is that i get images with webView not loaded... I tried to make setTimeout, but it doesn't help.
var cover = Titanium.UI.iOS.createCoverFlowView({
images: forflowImages
});
for (var k = start; k < cData.length; k++) {
r = Ti.UI.createView({});
for (var j = 0; j < child.objects.length; j++) {
tmp = Ti.UI.createWebView({
left : 10,
top : 10,
right : 10,
bottom : 10,
width : Ti.UI.FILL,
height : Ti.UI.SIZE,
willHandleTouches: true,
backgroundColor : '#fff2df',
});
tmp.html = obj.html;
no.add(tmp);
r.add(no);
}
}
r.addEventListener("load", function(e) {
blob = r.toImage();
});
forflowImages.push(blob);
}
cover.setImages(forflowImages);
With this code, coverFlowView doesn't have any views.
setTimeout(function() {
blob = r.toImage();
}, 500);
Also doesn't help, i have activity indicator on the page saved, content seems didn't have time to load before toImage function acted.
You are ordering things the wrong way, and you have multiple syntax errors, also you are listeneing for the load event on the wrong type of view, you shold be listeneing on the WebView, try this instead:
var forflowImages = [];
var container = // This should already be in the view stack somewhere
var cover = Titanium.UI.iOS.createCoverFlowView();
function loadListener(e) {
forflowImages.push(e.source.toImage());
if(forFlowImages.length == child.objects.length) {
// We have all the images for cover flow
cover.setImages(forflowImages);
}
}
var containerView = Ti.UI.createView();
for (var j = 0; j < child.objects.length; j++) {
var tmp = Ti.UI.createWebView({html : obj.html);
tmp.addEventListener("load", loadListener);
container.add(tmp);
tmp.repaint();
}
I removed some of your code that was syntactically incorrect and trimmed it down so it would be easy to understand. All this code does is add an event listener that handles the conversion of a webview to an image.

add each dataLabel a function on mouseover/mouseout

I want to add each dataLabel a (just call it "highlightPoint()") function on a mouseover event. It works, if I add this function to a single point.
chartObj.series[0].data[1].dataLabel.on("mouseover", function () {
chartObj.series[0].data[1].setState('hover');
});
It doesn't work if I loop threw my data points. I guess the reference to each individual point is incorrect or something like that.
jsfiddle-link
After you have looped through both data sets, i = 2 and k = 1. So the mouse events are always trying to use i=2 and k=1 to access the data point, which of course is out of bounds. See this fiddle: http://jsfiddle.net/bLvfS/1/
for (var i = 0; i < chartObj.series.length; i++) {
for (var k = 0; k < chartObj.series[i].data.length; k++) {
var onmouseover = function(u, j) {
return function() {chartObj.series[u].data[j].setState('hover');};
}
var onmouseout = function(u, j) {
return function() {chartObj.series[u].data[j].setState();};
}
chartObj.series[i].data[k].dataLabel.on("mouseover", onmouseover(i,k));
chartObj.series[i].data[k].dataLabel.on("mouseout", onmouseout(i,k));
}
}
I've added functions that get passed the current i,k pair and return the actual function you want to run on the mouse events. Maybe someone has a better solution... but it seems to work.
Problem is with closures, see working fiddle: http://jsfiddle.net/Fusher/bLvfS/2/
for (var i = 0; i < chartObj.series.length; i++) {
for (var k = 0; k < chartObj.series[i].data.length; k++) {
(function(i,k){
chartObj.series[i].data[k].dataLabel.on("mouseover", function () {
chartObj.series[i].data[k].setState('hover');
});
chartObj.series[i].data[k].dataLabel.on("mouseout", function () {
chartObj.series[i].data[k].setState();
});
})(i,k);
}
}

JQuery dialog box issue in Internet Explorer

I am using a UI dialog box to display a message.
It works well in Firefox and Google Chrome. However, when I test in IE versions the dialog box doesn't open.
Can any one tell what real problem is?
I had pasted my code below:
function check_selected(c) {
var count = c - 1;
var radios = document.getElementsByName('plan');
for ( var i = 0; i < radios.length; i++) {
if (radios[i].disabled) {
if (radios[i].checked) { // checked
$('#planalert').dialog({
modal : true,
autoOpen : true,
title : "Plan",
width : 650,
height : 150,
show : "blind",
hide : "scale",
});
var c = 0;
} else {
var c = 1;
}
}
}
;
if (c == 0) {
return false;
} else {
return true;
}
}
Try removing the trailing comma from the options object you're passing dialog:
$('#planalert').dialog({
modal:true,
autoOpen: true,
title:"Plan",
width:650,
height:150,
show: "blind",
hide: "scale" // <-----
});
Internet Explorer will choke on the extra comma, while other browsers may not.
Also, remove the semicolon (;) at the end of the for loop ending brace:
for (var i = 0; i < radios.length; i++) {
/* snip */
} // <--- semicolon not necessary
Additionally, you are attempting to define c multiple times inside of your function. You are passing it in to the function so your var c = ... statements actually aren't having the effect you intend. You should either use another variable (which I would recommend rather than mutating the parameter you are passed), or remove the var statements from inside the if block.
Additionally, your loop is really only setting c for the last, disabled radio button. Is this what you intended?
Anyway, here is how I would re-write it (without attempting to fix the logical error above). Be sure to use tools like JsHint to check your JavaScript for probems:
function check_selected(c){
var count=c-1;
var radios = document.getElementsByName('plan');
var isChecked = 0;
for (var i = 0; i < radios.length; i++) {
if (radios[i].disabled) {
if (radios[i].checked){ // checked
$('#planalert').dialog({
modal:true,
autoOpen: true,
title:"Plan",
width:650,
height:150,
show: "blind",
hide: "scale"
});
isChecked = 0;
} else{
isChecked = 1;
}
}
}
return isChecked;
}

Resources