3

Suppose I have an anchor in my page like :<a href="#header" id="anchor">turn to header</a> then I also set a button in my page <input type="button" value="triger anchor"> .What I want to do is that ,when I click the button ,it will triger the anchor's default click event ,as the page turn to "header".So I write $("input").click(function(){$("#anchor").trigger("click");}); But it seems doesn't work .So how can I achieve that?Thank you

hh54188
  • 14,027
  • 31
  • 107
  • 178

5 Answers5

5

Try This, working for Me !!

$("#anchor").get(0).click();

This will call default click of the anchor.

Aurelio De Rosa
  • 21,228
  • 8
  • 47
  • 70
Usman Younas
  • 1,273
  • 15
  • 20
4

Please see this answer.

Instead of trying to trigger the click event, try setting the window.location property:

window.location = '#header';

Or perhaps:

$("input").click(function() {
  window.location = $('#anchor').attr('href');
});
Community
  • 1
  • 1
sje397
  • 40,327
  • 7
  • 84
  • 103
0

jQuery does not have a way to trigger the native DOM event directly.

To do that, you can use the plain old standard DOM methods:

var evt = document.createEvent("Event");
evt.initEvent("click", true, true);
$('#anchor').get(0).dispatchEvent(evt);

For support of IE8 or earlier, you need to use the IE-specific event methods createEventObject and fireEvent.

chowey
  • 8,318
  • 6
  • 49
  • 77
0

You can Also use to trigger click/any events

$('#bycategory').click(function(){
  alert('triggered');
});
$('#bycategory').triggerHandler("click");
Elamurugan
  • 3,154
  • 13
  • 58
  • 103
-1

You have a spelling error. Please use:

{$("#anchor").trigger("click");});
Rob Hruska
  • 115,151
  • 29
  • 164
  • 188
Andrei Andrushkevich
  • 9,845
  • 4
  • 30
  • 42