What methods can I use to obtain negative numbers through swipe detection?

In my code, I am using three variables. The first one is x which serves as the starting point, followed by myCount which counts the number of swipes a user performs, and finally, dist which calculates the distance from the initial point.

I want to set myCount to -1 if the swipe (dragging on mobile) takes the user more than -201 units to the left, indicating a negative movement. While storing positive numbers works correctly for right swipes, it fails to store negative values effectively.

Is there any solution to address this issue?

This is the progress I have made so far:

CodePen
$(function stripeAnimeModule() {
  // Variables
  var screen = $('.page1'),
    buttons = $('.buttons').find('.button'),
    myCount = 1,
    x,
    dist;
  // Functions
  function clicked(e) {
    if ($(this).hasClass('prev')) {
      myCount -= 1;
      console.log(myCount, 'this is clicked');
    } else {
      myCount += 1;
      console.log(myCount);
    }
  }

  function touchStart(e) {
    return x = e.touches[0].pageX;
    e.preventDefault();
  }

  function touchMove(e) {
    var drag = e.touches[0].pageX;
    var dist = Math.sqrt(x + drag);
    e.preventDefault();
  }

  function touchEnd(e) {
    var dist = e.changedTouches[0].pageX - x;
    if (dist < Math.abs(-200)) {
      myCount = myCount;
      console.log('nothing', dist, myCount);
    } else if (dist > 201) {
      myCount += 1;
      console.log('distance is: ' + dist, x, 'myCount is: '+ myCount);
    } else if (dist > -201) {
      myCount -= 1;
      console.log('distance is: ' + dist, x, 'myCount is: '+ myCount);
    }
    e.stopPropagation();
    e.preventDefault();
  }

  buttons.on({ click: clicked });
  screen.bind({ touchstart:touchStart, touchmove:touchMove, touchend: touchEnd });
})
* {
  margin: 0;
  padding: 0;
}
ul li {
  list-style: none;
}
a {
  display: block;
}
.page1 {
  position: absolute;
  width: 100vw;
  height: 100vh;
  background-color: grey;
}
.buttons {
  z-index: 1;
}
.prev {
  position: absolute;
  left: 0;
  margin: 0 40px;
}
.shrink {
  position: absolute;
}
.next {
  position: absolute;
  right: 0;
  margin: 0 40px;
}
<div class="page1" href="#"></div>
<ul class="buttons">
  <li class="button prev">Prev</li>
  <li class="shrink"></li>
  <li class="button next">Next</li>
</ul>
<br><br><br><br><br><br><br><br><br><br><br><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №1

$(function uniqueStripeAnimeModule() {
  // Variables
    var screen = $('.page1'),
    buttons = $('.buttons').find('.button'),
    myCount = 1,
    x,
    dist;
  // Functions
    function clicked(e) {
      if ($(this).hasClass('prev')) {
        myCount -= 1;
        console.log(myCount, 'this is clicked');
      } else {
        myCount += 1;
        console.log(myCount);
      }
    }
    function touchStart(e) {
      return x = e.touches[0].pageX;
      e.preventDefault();
    }
    function touchMove(e) {
      var drag = e.touches[0].pageX;
      var dist = Math.sqrt(x + drag);
      e.preventDefault();
    }
    function touchEnd(e) {
      var dist = e.changedTouches[0].pageX - x;
      if (dist > 201) {
        myCount += 1;
        console.log('distance is: ' + dist, x, 'myCount is: '+ myCount);
      } else if (dist < -201) {
        myCount -= 1;
        console.log('distance is: ' + dist, x, 'myCount is: '+ myCount);
      } else {
        myCount = myCount;
        console.log('nothing', dist, myCount);
      }
      e.stopPropagation();
      e.preventDefault();
    }
    buttons.on({click: clicked});
    screen.bind({touchstart:touchStart, touchmove:touchMove, touchend: touchEnd});
})
* {
  margin: 0;
  padding: 0;
}
ul li {
  list-style: none;
}
a {
  display: block;
}
.page1 {
  position: absolute;
  width: 100vw;
  height: 100vh;
  background-color: grey;
}
.buttons {
  z-index: 1;
}
.prev {
  position: absolute;
  left: 0;
  margin: 0 40px;
}
.shrink {
  position: absolute;
}
.next {
  position: absolute;
  right: 0;
  margin: 0 40px;
}
<div class="page1" href="#"></div>
<ul class="buttons">
  <li class="button prev">Prev</li>
  <li class="shrink"></li>
  <li class="button next">Next</li>
</ul>
<br><br><br><br><br><br><br><br><br><br><br><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Please review and confirm if this meets your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Handling AJAX requests in ASP.NET for efficient communication

I'm in the process of setting up ajax communication between a JavaScript frontend and an ASP.NET backend. While researching, I came across this sample code on w3schools: function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatecha ...

How can the session user object be modified after logging in?

I've encountered a strange issue and I'm puzzled about its origin. In my Next.js app, I make use of the next-auth library to implement the authentication system. Initially, everything seems fine - I can successfully sign in by verifying the cred ...

Avoiding the selection of HTML canvas objects

I am currently working on customizing my homepage with an interactive animation. However, I am facing some challenges in integrating it seamlessly into the page. You can view the progress at . My main issue is preventing the canvas object from being select ...

Is it possible to enable password authentication on Firebase even if the user is currently using passwordless sign-on?

In my frontend JS project, I have integrated Firebase for web and am utilizing the passwordless (email link) authentication method for users. I am now interested in implementing password sign-on for an existing user who is currently using passwordless si ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...

Exploring the world of Node.JS and AngularJS through the integration of API routes

Currently, my backend is built using Node.JS with Express and serving as my API servlet. On the frontend, I'm utilizing AngularJS for the user interface. After numerous searches on Google, I was able to resolve an issue where I faced challenges using ...

Advanced Techniques: Leveraging Master Layouts, Partial Rendering, and JavaScript Function

Trying to understand the sequence of events when a master page, partials, and JavaScript code are involved. Imagine having a Master page with scripts: <%@ Master Language="C#" ... %> <head> <asp:ContentPlaceHolder ID="HeadContent" run ...

Troubleshooting Alignment Problem of Maximize and Close Icons in RadWindow Using ASP.Net

Currently, I am utilizing telerik radwindow to showcase a PDF document. The window seems to be functioning correctly, but there is an issue with the alignment of the maximize and close icons. Ideally, they should appear in the same row, however, they are b ...

What is the best way for a background-image to determine its height in CSS?

I am currently working on a website project and I would like to include my title using a background-image because it uses a unique font. In my design class, we were taught that this is the best approach. However, I am struggling with setting the correct di ...

SignalR's postback interrupts the functionality of jQuery actions

On my screen, I have a widget that updates data and changes its class based on server-side interactions. It also responds to mouse clicks. To notify multiple clients of updates simultaneously, I'm using SignalR. The problem arises when I wrap everythi ...

What is the best way to adjust the width of a button to match the size of its

Is there a way to make a button automatically adjust its width to the parent div it is nested in? . Below is the code (html structure) for reference: <div class="drp"> <button class="drp-btn" id="i-drp-btn">m/s</button> <div i ...

Organize tabs with ease in the bootstrap-tabdrop plugin

My webpage features a navigation bar along with the bootstrap-tabdrop plugin, which places tabs in a dropdown menu if there are too many to display on one line. The main objective is: No action when navigating through currently displayed tabs. Clicking o ...

Unable to integrate the datepicker module into angular.js framework

I encountered an issue when trying to integrate the angular-datepicker module using angular.js. Error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.6/$injector/modulerr?p0=Channabasavashwara&…0at%20d%20(http%3A%2F%2Fodite ...

Utilizing jQuery and AJAX for submitting multiple POST requests

Experiencing a problem with posting data via AJAX using a drag and drop interface. The data is being sent to the POST URL as intended, but there's a recurring issue where the POST request occurs twice, causing the processing URL to handle the data aga ...

Determining the precise margin within a nested div structure

Hopefully, my description of a "nested div" was accurate. My current situation involves an image within a div structured like this: content -> content-inner -> column_left I'm struggling to start the image at 0 px (the extreme left side of th ...

The border class in Bootstrap 4 seems to be malfunctioning when it comes to the top

I'm struggling to add a border to a div using Bootstrap 4. When I try using only the border property, it looks strange, and when I use other properties, no border appears. Here is the code snippet: I even tried with the beta 2 version. If there is s ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

Adjust the horizontal background-position transition for color change while scrolling using jQuery and CSS

I came across a fascinating website - - where the background-position changes on scroll() from a linear gradient with two colors to smoothly slide one color off the screen. While I grasped how they achieved the split colors using linear-gradient, I'm ...

Checking if a variable is true with jQuery

Check out this snippet of code: <main class="ok">My text</main> <script> $(document).ready(function() { if ( $('body').not('main.ok') ) { // or if ( Boolean ( $('main.ok') ) == false ) { ...

Error: The function getAuth has not been defined - Firebase

I have included the code snippets from index.html and index.js for reference. The analytics functionality seems to be working fine, but I am facing an issue with authentication due to an error during testing. Thank you for your help. index.html <script ...