user1767586
user1767586

Reputation: 458

Using click() on links in Android Stock Browser not working

I want to trigger a click on a link with JavaScript but have problems getting it to work on the Android Stock Browser. The following code works fine in Chrome (Desktop, Mac) and Safari (iOS) but not in the Android Stock Browser (Samsung Galaxy S3):

<a href="test" id="a">One</a>
<a href="test" id="b">Two</a>

<script>
document.getElementById('a').addEventListener("click", function (e) {
    e.preventDefault();
    document.getElementById('b').click();
});

document.getElementById('b').addEventListener("click", function (e) {
    e.preventDefault();
    alert("test");
});
</script>

http://jsfiddle.net/xYfdF/7/

When replacing the links with buttons it starts working on Android as well: http://jsfiddle.net/xYfdF/8/

Any idea what the problem is or how to achieve this otherwise?

Upvotes: 0

Views: 3564

Answers (2)

Tomas Bartalos
Tomas Bartalos

Reputation: 1276

I found the solution here. Its pure JS, not jquery, but might help to solve missing click() on android stock browsers:

<a href="http://stackoverflow.com/" id="link">click here</a>

<script type="text/javascript">
    //same as: document.getElementById("link").click()
    var clickEvent = document.createEvent('MouseEvent');
    clickEvent.initEvent('click', true, true);
    document.getElementById("link").dispatchEvent(clickEvent);
</script>

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

you need to convert your click events to touch events using Jquery like below

<script type="text/javascript">
    jQuery(document).ready(function() 
    {
       jQuery('#a').bind("touchstart touchend touchmove click",function(event) 
       {
    event.preventDefault();
         jQuery('#b').click();
       });

      jQuery('#b').bind("touchstart touchend touchmove click",function(event) 
       {
    event.preventDefault();
         alert('Test');
       });
    });
 </script>

Upvotes: 1

Related Questions