-1

I have an href that I want to be clicked automatically on page load. This is the HTML:

<a href="http://www.google.com" id="foo">YahOO</a>

and this is the script part:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#foo").trigger('click');
    });
</script>

But when I load the page nothing happens. Am I using the wrong ajax lib or what is wrong with this code?

chris
  • 4,827
  • 6
  • 35
  • 53
Rares Biris
  • 195
  • 1
  • 4
  • 19

1 Answers1

0

You need to use jQuery('#foo')[0].click(); to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger() jQuery method.

Note: DOM Level 2 .click() doesn't work on some elements in Safari. You will need to use a workaround.

http://api.jquery.com/click/

Post from jQuery.trigger('click') not working

Community
  • 1
  • 1
pie3636
  • 795
  • 17
  • 31
  • 1
    ... and why not use redirection? What sense does it make to click a link outside of testing purposes? – chris polzer Oct 12 '15 at 14:50
  • 2
    @chrispolzer probably OP is just experimenting for later delegating/duplicate-nesting the click to an image or other elements. There's lots of use-cases. – Roko C. Buljan Oct 12 '15 at 14:51