AngularJS directive containing a mousedown event handler that never triggers the click event

I have developed a custom directive that triggers the mousedown/touchstart and mouseup/touchend events to apply/remove a css3 transform (press/release effect) to the element.

It functions perfectly in desktop Chrome and IE, as well as iOS 7 and 6, but on Android 4.4.2 the transform is displayed without the click event being triggered to actually navigate.

The only workaround I found is to click/tap rapidly on the element. It seems like the click event is somehow being blocked or dismissed when tapping at a normal speed.

I have tried applying the directive to divs within <a> tags and divs with an ng-click directive - unfortunately, neither approach works.

EDIT: There is one scenario where it fails to work in all browsers - if the div I attach the directive to also has an ng-click attribute. However, if I add a nested div one level down in the DOM and apply the directive to that div, everything works fine.

Below is an example of a div wrapped in a link

<a ng-href="#/concept/{{conceptOfDay.id}}">
  <div class="contentBox" touch-tilt>
      <i class="fa fa-2x icon fa-calendar-o"></i>
      <div class="itemTitle">concept of the day</div>
      <div class="itemSubTitle">{{conceptOfDay.title}}</div>
  </div>
</a>

And here is the directive code snippet

angular.module('app').directive('touchTilt', ['$document', function ($document) {

    var directive = {
        restrict: 'A',
        link: function (scope, element, attr) {

            function mousedown(event) {
                var translateString = "perspective(800px) rotateX(0deg) rotateY(0deg) translateZ(-30px)";
                element.css('transform', translateString);
                $document.on('touchend mouseup', mouseup);
            }

            function mouseup(event) {
                var idleCss = "perspective(800px) rotateX(0deg) rotateY(0deg) translateZ(0px)";
                element.css('transform', idleCss);
                $document.off('touchend mouseup', mouseup);
            }

            element.on('touchstart mousedown', mousedown);
            element.click(function () { alert('click event handled'); })
        }
    };
    return directive;
}]);

Answer №1

When transitioning to Android or touch devices, utilizing the ngTouch module is typically recommended. Touch devices often have a delay, which is discussed in this documentation:

https://docs.angularjs.org/api/ngTouch

Your example may be missing some elements or implemented differently from how I would do it, so I won't comment on that specifically (I prefer using ngClick explicitly).

In any case, incorporating the ngClick directive from ngTouch should enhance the functionality of touch screens. I encountered a similar issue and found that including angular-touch made a significant difference.

Without information on the libraries you are using, I may unintentionally repeat some points.

Answer №2

When working within the link function, it's important to note that simply declaring handler functions like mousedown and mouseup isn't enough. You must also ensure they are properly set up to be triggered. This can be done by either adding ng-click directly in the markup or binding the element to the event listeners within the link function itself.

// (Within the link function)
element.bind('mousedown', function(){
    console.log('User clicked on document');
  });

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

Adding a SpotLight to Camera in ThreeJS: A Step-by-Step Guide

Trying to add a flashlight effect using Three.js r105 I'm attempting to attach a SpotLight to the camera to achieve a "Flashlight" effect. However, once I connect the SpotLight to my Camera, the light seems to completely stop working. What could be t ...

"Troubleshoot: Issue with React class component's setState not correctly updating

Hey there! I could really use some help with the issue I'm facing: So, I have a React class component that extends React.Component and it has a method that allows me to set its state whenever I want. I understand that passing a prop to the component ...

Implementing a directive in the form of the md-dialog

Hello everyone, I am facing a challenge in trying to incorporate code for a dialog within a directive. To elaborate: $mdDialog.show({ ..... template: '<my-directive></my-directive>', ..... }) And naturally, "my directive" would be ...

Is it possible to develop an application that, with just one click on the icon, opens a webpage in the browser?

I have developed a mobile-friendly website that offers most of the functionality of an app. However, there are still users who prefer having an actual 'app' on their phones for quicker access, rather than opening their browsers and typing in the ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

"Encountering a Syntax Error When Using request.post in Dojo Framework on Button Click

Here are three questions to consider: 1) What strategies can be utilized to streamline this code and reduce nesting and quote-related complications? 2) Are there any suggestions for addressing the parsing error mentioned below? I've already tested sep ...

Upon refreshing the page, the React application alters the font style

While working on my ReactJS application, I noticed that the font changes after the page loads and then reloads. Take a look at the examples below: Before reloading (press f5): https://i.sstatic.net/tJFjU.png After reloading (press f5): https://i.sstati ...

Having trouble clearing a div with Jquery

I'm having trouble emptying the am-container with my jQuery code. Here is what I currently have: jQuery(document).find("div[id='am-container']").html(''); Below is the HTML structure: <div class="mid-part-right"> <div ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

Dynamic field refreshed on server side upon second button press

I'm encountering an issue where a hidden field that I update via Javascript only reflects the new value after clicking a button twice. Surprisingly, I can view the updated hidden field value when inspecting it through the browser. Default.aspx <s ...

Making an AJAX request to a different domain

My understanding is that the AJAX cross-domain policy prevents me from simply making a call to "http://www.google.com" using an AJAX HTTP request and then displaying the results on my website. I attempted to use the dataType "jsonp", which theoretically s ...

The jQuery Validate Plugin only validates emails when the user moves away from the input field

Resolved: Upon inspecting my version of jquery-validate.js, I discovered that it was missing the onkeyup handler. Despite using version 1.12 Opre, which should have had this functionality according to its Github history from 2013, it seemed like there may ...

JavaScript Regular Expression for separating a collection of email addresses into individual parts

I am very close to getting this to work, but not quite there yet. In my JavaScript code, I have a string with a list of email addresses, each formatted differently: var emailList = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Looking for assistance in extracting images from Craigslist

After exhausting all my options, I've managed to retrieve postUrl, date, title, price, and location. By visiting and running the code snippet below in the console, all the images are returned successfully. However, when I attempt to access it in my c ...

Changing the text displayed after a checkbox is checked

I am currently working on creating a form that includes both checkboxes and text entry fields. The goal is to have related text appear next to each checkbox when it is checked. However, my current code does not seem to be functioning as expected: HTML: & ...

What are the steps for accessing a server-side WebControl from the client side?

Issue Overview: I am facing a problem with managing different types of input values in my dialog box. Depending on the selection from a dropdown list, the required input could be simple text, a date, or specific data from a database. I have successfully i ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

Performing server-side code execution while Node.js is functioning

Currently, I am working on developing a messaging app similar to Slack as a practice project. One of the key features I want to include is allowing users to create their own unique messaging space. Each time a user creates a new messaging space, a unique k ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...