0

I have a simple anchor element like below:

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

Below is JS code:

$(document).ready(function() {
    $(".foo").trigger('click');
});

Why is the click code not getting executed?

http://jsfiddle.net/L7vaLrwk/

Shane
  • 5,517
  • 15
  • 49
  • 79
  • 1
    Have you tried it somewhere other than jsfiddle? – Musa Apr 11 '17 at 15:52
  • 4
    Possible duplicate of [Jquery how to trigger click event on href element](http://stackoverflow.com/questions/7999806/jquery-how-to-trigger-click-event-on-href-element) – JJJ Apr 11 '17 at 15:54
  • 1
    If you don't have an event handler assigned to the anchor there is nothing for jquery to trigger – scrappedcola Apr 11 '17 at 15:55
  • 1
    `.trigger` doesn't trigger default behavior. Try something like `$(".foo")[0].click();` (not error proof). Actually, that is really not a good way to acheive what you want... – Karl-André Gagnon Apr 11 '17 at 15:55
  • *Why* do you want to do this? What are you trying to do? What problem are you trying to solve? – gen_Eric Apr 11 '17 at 16:05

2 Answers2

2

Instead of using .trigger() try using .click() and target the element by type and classname.

HTML

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

Javascript

    $(document).ready(function() {
      $('a.foo')[0].click()
    })
Stefan
  • 2,961
  • 1
  • 22
  • 34
0

You can try this way,

HTML
<a href="http://www.example.com" class="foo" id="fooTest">YahOO</a>

JavaScript
document.getElementById('fooTest').click();

Added an id to the link to uniquely identify it, and using plain javascript to simulate a click.
Have replaced google.com with example.com as google doesn't open inside a iframe

You can check working example here on jsFiddle.

Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
  • I downvoated because he asked how to target by class and do it with jQuery. The HTML should have to change to answer the question. – Stefan Apr 16 '17 at 14:26
  • @stefan, He tried with `jQuery`, but I can't see he mentioned of `jQuery` only solution. – Gaurav Gandhi Apr 17 '17 at 03:44
  • Either way the html shouldn't need to change for the solution, you could have used `getElementsByClassName` – Stefan May 11 '17 at 20:46