I was testing out the example for multi touch in canvas from Mozilla https://developer.mozilla.org/en-US/docs/Web/Guide/Touch_events
Here's the issue I am facing: the identifier attribute for Touch interface ALWAYS shows integer value of 0 on every single touch point on laptop (I am using Google Chrome Version 26.0.1410.64 m), which is a touch ultrabook.
According to the specs, identifier should be unique for each touch but it shows up as 0 for every new touch point on the canvas.
Please help me understand what's causing it because I want to use the identifier unique value to map it to different colors and make a paint on touch canvas like application.
In response to your comment, I take it you're referring to this bit of code in particular:
function ongoingTouchIndexById(idToFind) {
for (var i=0; i<ongoingTouches.length; i++) {
var id = ongoingTouches[i].identifier;
if (id == idToFind) {
return i;
}
}
return -1; // not found
}
As you can see, this function either returns the index of a given id (if a particular Touch hasn't ended yet, since the handler was last called), or returns -1.
The code page you linked to is pretty straight forward, IMO: Each time a new touchstart event is registered, the id's of on-going (or past) touch events are checked and the corresponding ids are removed from a global (evil) array. There's a ton of reasons why this is done, but I'll leave those for you to find (or ask a follow-up question about, once you've tried to familiarize yourself with the code).
The identifier is unique for each distinct changedtouch. Now, you didn't provide the code you're using, but my guess would be that you're not getting the unique identifier from the right place:
var ids = [];
for (var i=0;i<e.changedTouches.length;i++)
{
ids.push(e.changedTouches[0].identifier);
}
console.log(ids);
If you're touching with more than 1 digit, ids should contain a distinct id for each touch.
I might be barking up the wrong tree altogether here, but again: add your code to the question so we can be sure. But you could be reassigning the id over and over, only leaving you with the value for the last Touch in the changedTouches array.
You could also be trying to get the identifier directly from the event object. Or you could be doing something else, all the same.
Check your console, log the event object and check the changedTouches property of that event.
Related
To reproduce, click on the red exit button, then on the 2nd button.
https://jsfiddle.net/2q7yknrv/1/
You will see no video is appearing.
How would the for loop code be adjusted to allow for .playSingle2 video to appear?
How exactly would this be done in the code?
Would I be able to tell it to skip over it?
You do see it is not appearing on the screen, right?
function onYouTubeIframeAPIReady() {
let playlists = Array(3);
playlists[1] = "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g";
for (let i = 1; i <= 3; i++) {
let playvars = {}
if (playlists[i]) {
playvars.playerVars = {
playlist: playlists[i]
};
}
players.add(".playSingle" + i, playvars);
}
players.add(".playSingle2", {
playerVars: {
listType: "playlist",
list: "PLYeOyMz9C9kYmnPHfw5-ItOxYBiMG4amq"
}
});
}
Debugging Code
This question is a good example as to why learning how to debug your own code is critical to solving issues.
Let's start with what can be done to debug. OP provided two links (which are not minimal, reproducible examples)
Working: https://jsfiddle.net/4x6e3am5/
Not working: https://jsfiddle.net/2q7yknrv/1/
To debug I first took the two examples and did a simple text comparison (tools like DiffChecker are useful for this). This showed me what changed. And there were a couple of changes that stood out so the next thing I did was add some console.log() lines to follow the code as it attempted to add a player. This revealed that the playerOptions parameter being passed was empty, meaning the playlist information was never passed.
Upon digging further I noticed an important change. The one that does work changed this line in the for loop:
players.add(".playSingle1" + i, playvars);
to this:
players.add(".playSingle" + i, playvars);
Why is this significant? Because in the first example, while looping it will try to add a player to the classes playSingle11, playSingle12, and playSingle13, none of which exist on the page. This means the loop does nothing as the elements it's trying to use don't exist and the rest of the code will execute as intended.
In the second example (which does not work), it will try to add a player for playSingle1, playSingle2, and playSingle3. What's important is playSingle2 gets called twice (once in the loop and again later in the same function). This creates your issue because you are calling playSingle2 twice. And so when you change the last call outside of the loop to a class called works, it seems to fix the issue because you are not calling playSingle2 twice anymore.
Evidence
This can be verified a few different ways.
The easiest is the remove your for loop entirely. You'll notice that the playSingle2 playlist loads as intended. You don't need the works class to make it work, as the for loop is causing the issue.
Another way is to use another class like playSingle4, as this class isn't called in your loop. It's not that a random class like works is really a fix but instead, your loop and the code outside of your loop is calling the same class creating an issue.
Issues With Player API Playlist
Let's first look at the for loop provided and step through it to understand what is wrong with it.
let playlists = Array(3);
playlists[1] = "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g";
for (let i = 1; i <= 3; i++) {
let playvars = {}
if (playlists[i]) {
playvars.playerVars = {
playlist: playlists[i]
};
}
players.add(".playSingle" + i, playvars);
}
First, it declares an array called playlists with 3 empty/undefined values.
Next, it sets the second index (as arrays start at a 0 index) to a string that is comma separated.
This means the array actually looks like this when we start the loop:
[undefined, '0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g', undefined]
Then, this for loop does 3 passes, each time taking an index from the playlists array and storing a value in a variable, then passing this to the add() method to add a player.
But, the issue is the array still has 2 empty/undefined values.
So the first and third players receive an empty playlist, while the second player gets initialized twice.
My assumption is you are trying to load both a preset playlist and a custom 'on-the-fly' playlist (a list of video IDs), which is not supported by the YouTube IFrame Player API.
The list and listType parameter will always take precedence over the playlist parameter if both are present.
Example 1: list and listType are declared first
Example 2: playlist is declared first
Both examples load the YouTube playlist, rather than the custom list of video IDs.
Code of Conduct
Stack Overflow is a question and answer site that is populated with volunteers. This means that when you have a question, you should be respectful of those trying to help. Many people here are taking time out of their day to provide help/knowledge/insight as well as solutions to problems.
If someone offers information that can help, do not harass or berate them. Almost always, that information was shared with the intention of helping solve the problem. If you need clarity, feel free to ask but remember users here are not paid and are helping when they have the availability to do so. Sometimes responses and answers can take time so always be patient.
what I need to do is to gather some data online via fetch and use the data to give the user infos and such (that I can do). In some cases, the fetch can return multiple results (an array of data), so I decided to create a element in the page to list all the names of the elements in the array (each element in the array is a sub-array with various infos, also a "name", which would be a location name).
I'm working on Chrome. All works, I store the data and this way I created another function to (theoretically) give the user the infos about the selected option in the listbox. If I call the function directly it works fine, meaning it returns all the infos it should. What actually doesn't work is the fact that this function returning infos should trigger on click/selecting any option from the list and it doesn't work. I don't get any error messages, it just does nothing.
What you see in this image is what happens when you click "filter" (it actually filters world locations detected with name similar to "Milano"), the user gets infos in the page and what you see in the right log side in the red square is returning the content of that array I mentioned (it contains data, so it's working), the index selected in the list (the last, so it's 5) and the coordinates of such selected location.
This happens just after the creation of the options because I directly call the function (returning data about the selected option), but if I use manually the list it just does nothing (as you see in the list, there's nothing logged after those coordinates).
I tried to create the options like this:
function createOption(text){
let listOption = new Option(text, text, true, true);
return listOption;
}
What I do directly to create the options in the list is a "for" loop for each element i in the array:
document.getElementById("keyword-results").append(createOption(data.data[i].station.name));
I also tried appendChild instead of append. As I said, this works, but the manual use of the list doesn't. What I declared is:
document.getElementById("keyword-results").addEventListener("onchange", selection());
being "selection()" the function returning the data.
function selection(){
let index = document.getElementById("keyword-results").selectedIndex;
console.log(index);
if (index > -1){
let currentResult = results.data[index];
let aqi = currentResult.aqi;
console.log(aqi);
document.getElementById("answer").innerHTML += `The estimated AQI [...]`;
let far = distance(currentResult.station.geo[0], currentResult.station.geo[1]);
if (far != null || far != undefined) {
document.getElementById("answer").innerHTML += `The estimated distance [...]`;
}
}
}
I also tried "change", "onclick" and "click" as methods to trigger the function but none of them works. Do you have any suggestions? I can't find anything useful here on stackoverflow nor on the web. If you want to check the whole code, this is my GitHub repository https://github.com/leorob88/pollution-forecast-API
document.getElementById("keyword-results").addEventListener("onchange", selection());
addEventListener expects a function as a second parameter, selection() is not a function but selection is.
When you use addEventListener, there is no such event named onchange its actually change
so it becomes:
document.getElementById("keyword-results").addEventListener("change", selection);
Reference.
(EDIT: I solved my issue! Though I still don't understand the situation I see in the debugger. See my answer for more details)
(TL;DR: index is always undefined when used with a certain array. Doubt that would be enough info, but maybe for someone who's experienced this before.)
So basically, I'm using an array in javascript, and I started noticing some odd behaviour, so I went to the debugger, and I found that a defined variable representing the index was being treated as undefined. It's ONLY the case with this specific array, and it's index. I don't get errors saying that it's undefined, but when I look in the debugger, it says it's undefined when I hover over the variable in the array call (but it's defined if I hover over it anywhere before the array call), and I'm getting bugs that make it clear that the array is not being used properly. It makes absolutely no sense to me, but maybe someone's encountered a similar issue.
Take this example of code, It's drawing a tilemap layer for my MapRenderer class. The culprit here is "this.Map.layers". When I go into this function in the debugger, layerIndex is defined if I hover over the function parameter, but if I hover over it on the array call, it says it's undefined, and the whole logic breaks.
DrawLayer(ctx, camPos, layerIndex)
{
// Get the map/tile position based on the camera position, to decide which tile to start drawing.
var mapCamPos = new Point(Math.floor(camPos.x/TILESIZE),
Math.floor(camPos.y/TILESIZE));
// Get the max tile position based on camera position, to decide where to stop drawing.
var camPosLimit = new Point(Math.ceil(this.DrawSize.x/TILESIZE)+mapCamPos.x,
Math.ceil(this.DrawSize.y/TILESIZE)+mapCamPos.y);
// loop through all tiles we need to draw using rows and columns.
for(var row=mapCamPos.y;row<this.Map.layers[layerIndex].height&&row<=camPosLimit.y;row++)
{
for(var col=mapCamPos.x;col<this.Map.layers[layerIndex].width&&col<=camPosLimit.x;col++)
{
var currentTileID = this.GetTileID(layerIndex, row, col);
if (currentTileID >= 0 && !isNaN(currentTileID))
{
var drawPos = new Point(((col*TILESIZE)-camPos.x), ((row*TILESIZE)-camPos.y));
this.Spritesheet.PlayFrame(currentTileID);
this.Spritesheet.Draw(ctx, drawPos);
}
}
}
}
This is happening in many instances of my code wherever I'm using that array. I want to add how this started, because all of this logic was working previously. I had my tilemap working with multiple csv files, which I loaded as 2d arrays into an array. Today, I decided to switch it all to use one json file, as it is simply cleaner (one file rather than one csv per map layer), and I can add extra properties and stuff in the future rather than just having the tileIDs. So, in the above example, this.Map gets initialized through an ajax call(using jquery) to read the json file, before DrawLayer ever gets called. Still, I don't see why this would cause this. Doing "mapRenderer.Map.layers" in the console tells me that it's a normal array, and when I try calling it normally from the console, it works fine. I'm so confused at this issue. I had literally the same function before and it worked, just that my array has changed a bit(it used to be just "this.Layers", instead of "this.Map.layers"), but it's still a normal array... I don't see why it would behave so differently just because it was generated via json...
Any help or explanations would be greatly appreciated, thanks.
I still don't understand the situation I see in the debugger, maybe it's a firefox bug, or feature I don't understand. But I managed to fix my issue. It was a basic logic bug: I'm using the "Tiled" map editor, and when you export those maps to CSVs, the tile IDs are zero-based, meaning empty tiles are -1. When you export to json, they aren't zero-based, meaning empty tiles are 0, which I failed to notice, and this was the root of all my current issues. If anyone can explain why the firefox debugger might say defined variables are "undefined" when you hover over them, that would still be good to know.
I am encountering very strange behavior in Javascript, which I have never seen before. Below is a general example of the problem I am seeing:
var myObject = {};
$.each(myDict,function(k,v){
myObject[k]={nodes:[],links:[]};
console.log(myObject[v]);
//then perform some calculations to create a var link and a var node
myObject[k].links.push(link);
myObject[k].nodes.push(node);
})
When I do the console.log(myObject[v]), it will show "Object {nodes: Array[0], links: Array[0]}", which is what is expected. However, when I expand that (in the console), it shows "links: Array[35]" and "nodes: Array[40]". I have also checked to make sure the links and nodes I am pushing have the correct values, and they do, however they do not even appear in myObject[k].link even immediately after they were pushed. Instead, the links and nodes mysteriously already in myObject[v] have random null fields all over the place, which is impossible, given that none of the links and nodes I generate have such field values.
I can't figure out why in the world myObject isn't empty. I have also tried deleting the object using "delete", but to no avail--I suspected this could be some memory management issue. This behavior is extremely odd. It is also worth nothing that if I change the dictionary field names, it works fine a single time, and then after that I encounter the same problem.
Has anyone encountered this problem before?
Push without mentioning [k] index.
myObject.links.push(link);
I'm using Jorn Zaefferer's Autocomplete plugin on a couple of different pages. In both instances, the order of displayed strings is a little bit messed up.
Example 1: array of strings: basically they are in alphabetical order except for General Knowledge which has been pushed to the top:
General Knowledge,Art and Design,Business Studies,Citizenship,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Displayed strings:
General Knowledge,Geography,Art and Design,Business Studies,Citizenship,Design and Technology,English,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Note that Geography has been pushed to be the second item, after General Knowledge. The rest are all fine.
Example 2: array of strings: as above but with Cross-curricular instead of General Knowledge.
Cross-curricular,Art and Design,Business Studies,Citizenship,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Displayed strings:
Cross-curricular,Citizenship,Art and Design,Business Studies,Design and Technology,English,Geography,History,ICT,Mathematics,MFL French,MFL German,MFL Spanish,Music,Physical Education,PSHE,Religious Education,Science,Something Else
Here, Citizenship has been pushed to the number 2 position.
I've experimented a little, and it seems like there's a bug saying "put things that start with the same letter as the first item after the first item and leave the rest alone". Kind of mystifying. I've tried a bit of debugging by triggering alerts inside the autocomplete plugin code but everywhere i can see, it's using the correct order. it seems to be just when its rendered out that it goes wrong.
Any ideas anyone?
max
EDIT - reply to Clint
Thanks for pointing me at the relevant bit of code btw. To make diagnosis simpler i changed the array of values to ["carrot", "apple", "cherry"], which autocomplete re-orders to ["carrot", "cherry", "apple"].
Here's the array that it generates for stMatchSets:
stMatchSets = ({'':[#1={value:"carrot", data:["carrot"], result:"carrot"}, #3={value:"apple", data:["apple"], result:"apple"}, #2={value:"cherry", data:["cherry"], result:"cherry"}], c:[#1#, #2#], a:[#3#]})
So, it's collecting the first letters together into a map, which makes sense as a first-pass matching strategy. What i'd like it to do though, is to use the given array of values, rather than the map, when it comes to populating the displayed list. I can't quite get my head around what's going on with the cache inside the guts of the code (i'm not very experienced with javascript).
SOLVED - i fixed this by hacking the javascript in the plugin.
On line 549 (or 565) we return a variable csub which is an object holding the matching data. Before it's returned, I reorder this so that the order matches the original array of value we were given, ie that we used to build the index in the first place, which i had put into another variable:
csub = csub.sort(function(a,b){ return originalData.indexOf(a.value) > originalData.indexOf(b.value); })
hacky but it works. Personally i think that this behaviour (possibly coded more cleanly) should be the default behaviour of the plugin: ie, the order of results should match the original passed array of possible values. That way the user can sort their array alphabetically if they want (which is trivial) to get the results in alphabetical order, or they can preserve their own 'custom' order.
What I did instead of your solution was to add
if (!q && data[q]){return data[q];}
just above
var csub = [];
found in line ~535.
What this does, if I understood correctly, is to fetch the cached data for when the input is empty, specified in line ~472: stMatchSets[""] = []. Assuming that the cached data for when the input is empty are the first data you provided to begin with, then its all good.
I'm not sure about this autocomplete plugin in particular, but are you sure it's not just trying to give you the best match possible? My autocomplete plugin does some heuristics and does reordering of that nature.
Which brings me to my other answer: there are a million jQuery autocomplete plugins out there. If this one doesn't satisfy you, I'm sure there is another that will.
edit:
In fact, I'm completely certain that's what it's doing. Take a look around line 474:
// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
/* some code */
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] )
and so on. So, it's a feature.