3

I have a link like this:

<a href="index.html" class="link_to_home" target="_blank" style="display:none;">home</a>

I use:

$('.link_to_home')[0].click();

But it doesn't work with the iOS and Android browsers.

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
user3230788
  • 31
  • 1
  • 4

2 Answers2

0

Try this, the normal click method does not work on iOS browsers. Use DOM method Instead (its Cross Browser)

HTML

<a href="index.html" id="yourAnchorId" class="link_to_home" target="_blank" style="display:none;">home</a>

Javascript

var ele = document.getElementById('yourAnchorId');
var click_ev = document.createEvent("MouseEvent");
click_ev.initEvent("click", false /* bubble */, true /* cancelable */);
ele.dispatchEvent(click_ev);
ExcellentSP
  • 1,529
  • 4
  • 15
  • 39
Voonic
  • 4,667
  • 3
  • 27
  • 58
  • @user3230788 Try repacing MouseEvent with HTMLEvents, eg document.createEvent("HTMLEvents"); – Voonic Jan 24 '14 at 08:04
0

As you know, on Android, for every other element but anchor tags, simply calling click() works. On Android for anchor tags, you need to trigger a start and end touch event on that element. Source (Typescript shown - a superset of Javascript):

// Example call to trigger a tap (jquery will interpret as a click) on an elementX: Gremlins.tap([{ x: 1, y: 1 }], document.getElementById('yourAnchorId'));

    /**
     * trigger a touchevent
     * @param touches  Array of touch positions within the element (for a sequence of touches).  Ex: [{ x: 1, y: 1}]
     * @param element
     */
    private static tap(touches, element) {
        Gremlins.triggerTouch(touches, element, 'start');

        setTimeout(function () {
            Gremlins.triggerTouch(touches, element, 'end');
        }, 50);
    }

    /**
     * trigger a touchevent
     * @param touches  Array of touch positions within the element (for a sequence of touches).  Ex: [{ x: 1, y: 1}]
     * @param element
     * @param type - "start" or "end" of the process of 1 tap event
     */
    private static triggerTouch(touches, element, type) {
        var touchlist = [],
            event:any = document.createEvent('Event');

        event.initEvent('touch' + type, true, true);

        touches.forEach(function (touch, i) {
            var x = Math.round(touch.x),
                y = Math.round(touch.y);
            touchlist.push({
                pageX: x,
                pageY: y,
                clientX: x,
                clientY: y,
                screenX: x,
                screenY: y,
                target: element,
                identifier: i
            });
        });

        event.touches = (type == 'end') ? [] : touchlist;
        event.targetTouches = (type == 'end') ? [] : touchlist;
        event.changedTouches = touchlist;

        element.dispatchEvent(event);
    }
Rick Mortensen
  • 343
  • 2
  • 8