Randomblue
Randomblue

Reputation: 116433

Click anchor, and be brought to linked page

I have a anchor on which I trigger a click with JavaScript. Please see this fiddle.

$(function() {
    $('a').click();
});

For some reason, triggering the click does not bring me to the page specified by the href attribute of the anchor.

How can I have the click event also bring me to the page linked by the anchor?

Upvotes: 0

Views: 49

Answers (2)

MLewisCodeSolutions
MLewisCodeSolutions

Reputation: 251

Seems to be something to do with jQuery and the trigger method, works fine when you change [object object] to [object]. Here is the fiddle. Enjoy!

$(function() {
    $('a').get(0).click();
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

It will not work like that, the call $('a').click(); is a short cut for $('a').trigger('click'); which tries to simulate a click action on the anchor element.

But the simulation is not absolute, though it will fire the registered event handler it will not completely simulate a use click trigger the default action.

As per the jquery doc for trigger

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

and

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

So I don't think it is possible to completely simulate a user action and trigger a redirection using this method

Upvotes: 1

Related Questions