RayLoveless
RayLoveless

Reputation: 21058

How to simulate anchor link click

I'm trying to trigger a link click for .jquery. Does someone know why the following doesn't work.

<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html lang="en"> 
  <head> 
    <title>test</title>
  </head>
  <body> 
    <div>
       <a id="google_link" href="http://google.com" target="_blank">click to go to google</a>
    </div>
    <div id="google_link_proxy">click here to do the same as the link above</div>

    <script type="text/javascript">      
     $("#google_link_proxy").click(function(event){
         $("#google_link").click();
     });
    </script>
  </body>
</html>

Upvotes: 29

Views: 85058

Answers (6)

Vasfed
Vasfed

Reputation: 18454

This can be done without jQuery:

document.querySelector('#google_link').click()

Upvotes: 2

Roman Starkov
Roman Starkov

Reputation: 61402

The jQuery method completely ignores href:

$('#google_link').click(); // ignores href!

The native DOM method does the right thing:

$('#google_link')[0].click();

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Upvotes: 49

Wandering Zombie
Wandering Zombie

Reputation: 1121

If you use jQuery and the native DOM, the anchor can be clicked

// insert an <a> into document and click it **natively**
// (.get(0) returns the DOM element)
$('<a id="fred99" />').attr('href', '#david').attr('target', '_blank')
.text('LINK').appendTo('body').get(0).click();

// now we've clicked, tidy up
$('#fred99').remove();

Upvotes: 21

epascarello
epascarello

Reputation: 207511

Use click()

$("#google_link_proxy").click(
    function(){
        $("#google_link").click();
    }
);

fireEvent and observe is not part of jQuery API

Upvotes: 2

pixelbobby
pixelbobby

Reputation: 4440

Make sure you have your jQuery code wrapped in a ready block like so

$(document).ready(function(){/* your code here */});

This ensures scripts are fired after all the content and images are loaded.

Upvotes: 2

Jeff the Bear
Jeff the Bear

Reputation: 5653

Looks like your $("google_link_proxy") selector is off. Try $("#google_link_proxy").

You also need to close the observe call with }).

Those are the syntax errors with the code above though I don't think those functions are provided in jQuery by default.

Here is what I think you're after:

$("#google_link_proxy").click(function(event){
    window.open($("#google_link").attr('href'),'_blank')
});

Upvotes: 20

Related Questions