简体   繁体   中英

Detecting when user touches a link

I'm trying to detect when the user has touched a link within a web page versus when they have touched any other part of the page, but its not working - what happens is in the following code the alert "touched a non link" pops up wherever I touch, regardless of if its a link.

What is there a problem with this code?

function addListeners()
{  
    alert('adding listeners');

    // Attach the listener for touches on non-links to the document node
    document.addEventListener("touchstart", touchesOnNonLinksListerner, false);

    // Attach the listener for touches on links to the anchor nodes
    var links = document.getElementsByTagName("a");
    for (var index = 0; index < links.length; ++index)
    {
        links[index].addEventListener("touchstart", touchesOnNonLinksListerner, false);
    }
}; 

function touchesOnNonLinksListerner(event)
// Catches touches anywhere in the document
{
    alert("touched  a non link");
}

function touchesOnLinksListener(event)
// Listens for touches which occur on links, then prevents those touch events from bubbling up to trigger the touchesOnNonLinksListerner
{
    alert("touched a link");
    if (typeof event == "undefined")
    {
        event = window.event;
    }

    event.stopPropegation();
}

You have attached touchesOnNonLinksListerner to your links as well. Attach touchesOnLinksListener instead!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM