umpljazz
umpljazz

Reputation: 1222

jQuery click event not firing - ios home screen web app

Building a web application and having trouble getting a click event to fire. It works perfectly when running from a normal instance of Safari, but when running from the home screen, it fails.

$("a.applink").live('click', clickHandler);
var clickHandler = function(e) {
    console.log(e);
    e.preventDefault();
}

When running from the home screen, 'e' is empty. If I replace 'click' for 'touchend', it does work, but touchend doesn't give the correct behaviour (i.e. if you happen to touch a link to start a scroll, it triggers an unexpected click).

Is there a proper solution to this?

Upvotes: 1

Views: 1680

Answers (3)

brettish
brettish

Reputation: 2648

I know this answer is a tad late but incase anyone else stumbles across this question:

Add cursor: pointer; to the element's style if you are making an element "clickable" via JS. That will tell iOS to trigger click events.

Generally speaking, using touch event might interfere with scrolling.

Upvotes: 0

Krishna Kumar
Krishna Kumar

Reputation: 2131

First define clickHandler function and once it's declared then use $("a.applink").live('click', clickHandler); right now you are binding clickHandler to an event before it's declare,

Note: Order matter in this pattern.

var clickHandler = function(e) {
    console.log(e);
    e.preventDefault();
}

jQuery(function(){
    $("a.applink").live('click', clickHandler);
})

OR

Chnage your code like this

jQuery(function(){
    $("a.applink").live('click', clickHandler);
});

function clickHandler (e) {
    console.log(e);
    e.preventDefault();

}

Upvotes: 0

Thierry Blais
Thierry Blais

Reputation: 2858

Here's how I did it:

Essentially, when you navigate a page you're going to tap or scroll. (Well there are other things like pinch and slide put you can figure them out later)...

So on a tap your 'touchstart' will be followed by a 'touchend' On a scroll your 'touchstart' will be followed by a 'touchmove'

Using Jq 1.7... on other versions you can use .bind()

function nextEvent() {
    //behaviour for end
    $(this).on('touchend', function(e){
        /* DO STUFF */
        $(this).off('touchend');
        });
    //behaviour for move
    $(this).on('touchmove', function(e){
        $(this).off('touchend');
        });     
    }

$(element).on('touchstart', this, nextEvent);

Basically, when a 'touchstart' happens, I bind actions to 'touchend' and 'touchmove'.

'Touchend' does whatever I would want a tap to do and then unbinds itself 'Touchmove' basically does nothing except unbind 'touchend'

This way if you tap you get action, if you scroll nothing happens but scrolling..

Upvotes: 2

Related Questions