Recognize diagonal gestures(swipe) using Hammer.js - swipe

Is it possible to recognize diagonal swipe using Hammer.js?
I have gone through their documentation but didn't find anything saying about diagonal swiping or pan etc...

An object with a lot of info about the gesture is passed to every Hammer.js event callback (as described here in the API docs).
The eventObject.angle property is what you are looking for. Its values are between -180 and 180 (0 means RIGHT, -90 means UP, 90 means DOWN, 180 means LEFT).
So here's how you can recognize diagonal swipes:
var hammertime = new Hammer(domElement);
hammertime.get("swipe").set({ direction: Hammer.DIRECTION_ALL });
hammertime.on("swipe", function(eventObject) {
if(eventObject.angle < -90) {
//UP-LEFT SWIPE...
} else if(eventObject.angle < 0) {
//UP-RIGHT SWIPE...
} else if(eventObject.angle < 90) {
//DOWN-RIGHT SWIPE...
} else {
//DOWN-LEFT SWIPE...
}
});

For those who want an 8 way swipe (up, down, left, right, up-left, down-left, up-right, down--right) option using HammerJS. it's worth looking into using the angle in a range of values. The left option is the only clever one... since it's an OR statement rather than an AND statement.
var hammertime = new Hammer(domElement);
hammertime.get("swipe").set({ direction: Hammer.DIRECTION_ALL });
hammertime.on("swipe", function(e) {
let jResult = '';
switch(true) {
// LEFT
case (e.angle < -157.5 || e.angle > 157.5):
jResult = 'left';
break;
// RIGHT
case (e.angle > -22.5 && e.angle < 22.5):
jResult = 'right';
break;
// UP
case (e.angle < -67.5 && e.angle > -112.5):
jResult = 'up';
break;
// Down
case (e.angle > 67.5 && e.angle < 112.5):
jResult = 'down';
break;
// LEFT-Up
case (e.angle < -112.5 && e.angle > -157.5):
jResult = 'left-Up';
break;
// LEFT-Down
case (e.angle > 112.5 && e.angle < 157.5):
jResult = 'left-Down';
break;
// RIGHT-Up
case (-22.5 > e.angle && e.angle > -67.5):
jResult = 'right-Up';
break;
// RIGHT-Down
case (e.angle > 22.5 && e.angle < 67.5):
jResult = 'right-Down';
break;
default:
// code block
jResult = 'unknown'; // UNKNOWN - what happened?
}
console.log('--00--> Swipe: ' + e.direction + ' -- Dir is: ' + jResult);
this.lastSwipe = jResult;
});
Output is shown to console... your milage may vary.

Related

Pagination is not working in angular JS when the items is below 12 and more than 10

I am using this <github.com/michaelbromley/angularUtils-pagination> Url code. I can able to see the data coming to UI but the pagination is not working consistantly. when there are more than 12 items the pagination is working when there are are less than 12 and more than 10 pagination is not working properly. Please refer to the URL above and suggest a solution. we are suspecting the below code. But not sure where the issue is:
function generatePagesArray(currentPage, collectionLength, rowsPerPage, paginationRange) {
var pages = [];
var totalPages = Math.ceil(collectionLength / rowsPerPage);
var halfWay = Math.ceil(paginationRange / 2);
var position;
if (currentPage <= halfWay) {
position = 'start';
} else if (totalPages - halfWay < currentPage) {
position = 'end';
} else {
position = 'middle';
}
var ellipsesNeeded = paginationRange < totalPages;
var i = 1;
while (i <= totalPages && i <= paginationRange) {
var pageNumber = calculatePageNumber(i, currentPage, paginationRange, totalPages);
var openingEllipsesNeeded = (i === 2 && (position === 'middle' || position === 'end'));
var closingEllipsesNeeded = (i === paginationRange - 1 && (position === 'middle' || position === 'start'));
if (ellipsesNeeded && (openingEllipsesNeeded || closingEllipsesNeeded)) {
pages.push('...');
} else {
pages.push(pageNumber);
}
i++;
}
return pages;
}

Issue with sending periodic messages using discord.js

I get this issue
setInterval(function(){
var randommessage = Math.floor(Math.random() * 5) + 1;
var randomsentence = Math.floor(Math.random() * 10) + 1;
if(randommessage === 1){
console.log("Silence...")
} else {
if(randomsentence === 1){
client.channels.get('532065669718736906').send("Do you ever wonder why we were born... whats our purpose?")
} else if(randomsentence === 2){
client.channels.get('532065669718736906').send("So... you come here often?")
} else if(randomsentence === 3){
client.channels.get('532065669718736906').send("What is the point of this server?")
} else if(randomsentence === 4){
client.channels.get('532065669718736906').send("Why do i exist?")
} else if(randomsentence === 5){
client.channels.get('532065669718736906').send("Why are we still here... just to suffer..")
} else if(randomsentence === 6){
client.channels.get('532065669718736906').send("Begels are life!")
} else if(randomsentence === 7){
client.channels.get('532065669718736906').send("Banana Bros!!")
} else if(randomsentence === 8){
client.channels.get('532065669718736906').send("Is the number 3 a myth?")
} else if(randomsentence === 9){
client.channels.get('532065669718736906').send("*Shuffles through papers*")
} else if(randomsentence === 10){
client.channels.get('532065669718736906').send("In the end.. it doesnt even matter!")
} else {
client.channels.get('532065669718736906').send("randomness is gud")
}
}
}, 3000);
that is suppose to send periodic messages except I get the error
TypeError: Cannot read property 'send' of undefined
at Timeout._onTimeout (C:\Users\User\Documents\Discord Intro Bot\index.js:52:46)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7)
I've tried everything under the sun to try and fix this even finding the channel beforehand then sending to it, but it still thinks the channel does not exist.
I don't want to use the on message since my server is pretty inactive, and I'm using this to add a bit of emotion to the bot

Function inside JSX, is not returning the elements: ReactJS

I am trying to add extra rows on a table that is generated using results.map, but the code that I have added to generate the extra rows isn't executing. Does anyone know why this wouldn't work?
< tbody >
{
results.map(result => {
let rowNodes = [];
rowNodes.push(<td className="hidden">{result.itemCtrlType}</td>);
if (this.props.gridNumber == 1) {
rowNodes.push(<td className="in-td-item">{result.metric}</td>);
} else {
rowNodes.push(<td className="in-td-item hidden">{result.metric}</td>);
}
for (const hour in result) {
if (hour.indexOf('t') == 0 && hour.length == 3) {
let now = Date.now();
let d = new Date(now);
let hours = d.getHours();
let time = hours.toString();
if (hours < 10) {
time = 't0' + hours;
}
else {
time = 't' + hours;
};
let classname = "in-td";
if (hour == time && this.props.dateAdjust == 0) {
classname += " cell-timenow";
}
if (hour == 't23') {
classname += " table-lastcolumn";
}
let date = [pad(d.getMonth() + 1), pad(d.getDate()), d.getFullYear()].join('/');
rowNodes.push(<td key={hour} className={classname} >{result[hour]}</td>)
}
}
if (this.props.gridNumber == this.props.totalGrids) {
rowNodes.push(<td className="in-td-addcolumn in-td"></td>);
}
return <tr key={result.metric} onClick={this.handleClick}>{rowNodes}</tr>
})
}
{
() => {
console.log(this.props.rowsCount > results.length);
if (this.props.rowsCount > results.length) {
let diff = this.props.rowsCount - results.length;
var rowNodes = [];
for (let m = 0; m < diff; m++) {
rowNodes.push(<td className="hidden"></td>);
if (this.props.gridNumber == 1) {
rowNodes.push(<td className="in-td-item"></td>);
} else {
rowNodes.push(<td className="in-td-item hidden"></td>);
}
for (let n = 0; n < 24; n++) {
rowNodes.push(<td className="in-td"></td>);
}
if (this.props.gridNumber == this.props.totalGrids) {
rowNodes.push(<td className="in-td-addcolumn in-td"></td>);
}
return <tr>{rowNodes}</tr>
}
}
}
}
</tbody>
I have tried various combinations of wrapping it in divs or changing where it returns but nothing seems to work.
Anyone know why this isn't firing?
First of all, that is not a good way of organising code, instead of putting the function directly inside JSX, better to define it outside of render method and then call.
Solution:
Issue with your code is, you defined a function inside JSX, but you are not calling it, Use IIFE and call that function, also return null when if condition fails, Like this:
{
(() => {
console.log(this.props.rowsCount > results.length);
if (this.props.rowsCount > results.length) {
let diff = this.props.rowsCount - results.length;
var rowNodes = [], elements = [];
for (let m = 0; m < diff; m++) {
rowNodes = [];
rowNodes.push(<td className="hidden"></td>);
if (this.props.gridNumber == 1) {
rowNodes.push(<td className="in-td-item"></td>);
} else {
rowNodes.push(<td className="in-td-item hidden"></td>);
}
for (let n = 0; n < 24; n++) {
rowNodes.push(<td className="in-td"></td>);
}
if (this.props.gridNumber == this.props.totalGrids) {
rowNodes.push(<td className="in-td-addcolumn in-td"></td>);
}
elements.push(<tr key={m}>{rowNodes}</tr>);
}
return elements;
}
return null;
})()
}
Note:
Whenever execution find return statement inside for loop, it will immediately break the loop and return that result, so instead of using return use one more variable and put the tr inside that, Return the result only after for loop completion.
Suggestion:
Assign unique key to each dynamically created elements inside loop.
Check DOC.
Check this answer for more details about keys: Understanding unique keys for array children in React.js

Swipe UIImageView array loop

i am new here and I am also a beginner in Swift!
I am trying to create an UIImageView to swipe left and right, when i get to the last image the app crash, the same crash happen if i am in the first image and try to swipe to the right!
What i wanna do is when my array of Images reaches the last image send me back to the First image in a loop, can anyone help me please?
Thank you in advance!!!
Here is my code;
func swiped(gesture: UIGestureRecognizer) {
CATransaction.begin()
CATransaction.setAnimationDuration(animationDuration)
CATransaction.setCompletionBlock {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(self.switchingInterval * NSTimeInterval(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
}
}
let transition = CATransition()
transition.type = kCATransitionFade
chracters.layer.addAnimation(transition, forKey: kCATransition)
CATransaction.commit()
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right :
print("User swiped right")
// decrease index
imageIndex -= 1
// check if index is in range
if swipePosition > imageList.count-1{
// Do Nothing
} else {
swipePosition += 1
}
chracters.image = UIImage(named: imageList[imageIndex])
case UISwipeGestureRecognizerDirection.Left:
print("User swiped Left")
// increase index first
imageIndex += 1
// check if index is in range
if swipePosition == 0 {
//Do Nothing
} else {
swipePosition -= 1
}
chracters.image = UIImage(named: imageList[imageIndex])
default:
break;
//stops the code
}
}
}
First your condition seems to be amiguous, you can use swipePosition itself instead of imageIndex. Secondly your chracters.image should inside the if/else block. Below is the updated snippet. If you want to use imageIndex you can change it accordingly. Also added the code to switch from last image to first image and first image to last.
if swipePosition > imageList.count-1{
swipePosition = 0
chracters.image = UIImage(named:imageList[swipePosition]
} else {
chracters.image = UIImage(named:imageList[swipePosition]
swipePosition += 1
}
case UISwipeGestureRecognizerDirection.Left:
print("User swiped Left")
// check if index is in range
if swipePosition == 0 {
swipePosition = imageList.count-1
chracters.image = UIImage(named:imageList[swipePosition]
} else {
chracters.image = UIImage(named:imageList[swipePosition]
swipePosition -= 1
}

Angular - Delaying forEach

I have a problem. I am trying to create an animation, changing the color of several layers with a timeout between painted.
$scope.StartMovementsAnimation = function()
{
angular.forEach($scope.GameMovements, function(movement){
if (movement == "Green")
{
$scope.Green = true;
}
else (movement == "Orange")
{
$scope.Orange = true;
}
});
}
The problem I have is that I do not know how to stop or delay the flow loop. I'm pretty lost. I tried with $ timeout, sleep etc but does not work.
Any solution?
thanks
Don't use forEach. Use $timeout to repeat as many as the number of items in your GameMovements array.
Take a look at the following example. It is going to change className field from orange to green and vice versa till the variable left's value reaches 0.
$scope.className = "orange";
$scope.count = 0;
$scope.startAnimation = function() {
var left = 10
var ticker = function() {
if (left % 2 === 0)
$scope.className = 'orange'
else
$scope.className = 'green'
left -= 1
if (left > 0) {
$timeout(ticker, 1000)
}
}
$timeout(ticker, 1000)
}

Resources