2

I am trying to programmatically click a link in jQuery Mobile but its not working. Here is the page code.

<section id="welcome" data-role="page">

<div class="content" data-role="content">
<a id="myLink"  href="http://www.google.de" target="_blank">The link</a>
<input type="button" id="launcher" value="Launch the link"/>
</div>
</section>

and here is the correpsonding javascript code:

$(document).ready(function()
{
$("#launcher").bind("click",function()
{
    console.log("Inside the button click handler");
    $("#myLink").click();
});
});

Seems straightforward enough but I can,t seem to make it work.Any help is appreciated.

4 Answers 4

1

A possible reason for it not working is that there is another <a id="myLink"></a> in the DOM, but not in the active page. If that is the case, your code might be triggering the click handler on that element rather than the one you see on screen. Maybe using $.mobile.activePage.find("#myLink").click(); will work.

Also, you should avoid using $(document).ready() in jQuery Mobile.

0

Not really an answer to the question,but this can be a solution if you want to achieve only the link to be launched(and you dont want to execute the click handler you have defined for the link,if any)

$(document).ready(function()
{
$("#launcher").bind("click",function()
{
    console.log("Inside the button click handler");
    window.open($("#myLink").attr("href"),$("#myLink").attr("target"));
});
});
0

You should use a trigger, like so:

$('#mylink').trigger('click');

also, check your binding is actually being bound to an element. In JQM you should not rely on $(document).ready. Instead use $(document).bind('pageinit') . See here

0

I had the same problem. What worked for me was calling click() on the DOM object itself. Just add ”[0]” after the jQuery object.

Like this:

$(document).ready(function()
{
$("#launcher").bind("click",function()
{
    console.log("Inside the button click handler");
    $("#myLink")[0].click();
});
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.