jonathanpeppers
jonathanpeppers

Reputation: 26505

Javascript - Programmatically Click Anchor in iOS Safari

I working with an existing website, with some anchors tags like so:

<ul>
    <li><a id="answer-1" href="/" rel="0">Answer 1</a></li>
    <li><a id="answer-2" href="/" rel="1">Answer 2</a></li>
    <li><a id="answer-3" href="/" rel="2">Answer 3</a></li>
    <li><a id="answer-4" href="/" rel="3">Answer 4</a></li>
</ul>

I need to programmatically click one of these anchors depending on the user's selection.

On the desktop, in IE, this works:

document.getElementById('answer-1').click();

However, doesn't quite work in iOS safari, this results in a popup:

if (!document.getElementById('answer-1').click) alert ('Oh no!');

Best I can tell, they have some other javascript hooked up using to send the rel tag as an answer. Is there another way to programmatically click the anchor in iOS Safari? Or do I need to go digging in their javascript to find out what is being called when the anchor is clicked?

I have also tried this, which doesn't work:

window.location.href = document.getElementById('answer-1').href;

They must be doing more in Javascript somewhere (maybe jquery).

Upvotes: 1

Views: 8666

Answers (4)

zavi&#233;
zavi&#233;

Reputation: 4321

This problem occurred too with my Mac app when tested under Snow Leopard or Lion. Strangely it worked with Mountain Lion.

I solved the problem using jQuery.

$('#answer-1').click();

You may also give it a try if the site already loads jQuery!

Upvotes: -1

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

I've answered to a similar question where one needs to dispatch click event manually: Force link to open in mobile safari from a web app with javascript

You can apply that logic into your code.

Upvotes: 3

jonathanpeppers
jonathanpeppers

Reputation: 26505

It looks to me like there is not a way to call click() in mobile safari.

Using the dev-toolbar in Google Chrome, I was able to figure out the javascript function that is invoked when you click one of these anchors.

I was able to just call the function to get what I need.

I will wait a few days to mark the answer, as I would still like to know an alternative to click() in mobile safari.

Upvotes: 0

sciritai
sciritai

Reputation: 3758

Looks like the click function is not supported by Mobile Safari. document.getElementById('answer-1').click returns undefined which is why you get the alert. Try using .trigger()

Upvotes: 0

Related Questions