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,887
  • 32
  • 113
  • 184

5 Answers5

5

Try This, working for Me !!

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

This will call default click of the anchor.

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
Usman Younas
  • 1,323
  • 15
  • 21
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
  • 41,293
  • 8
  • 87
  • 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
  • 9,138
  • 6
  • 54
  • 84
0

You can Also use to trigger click/any events

$('#bycategory').click(function(){
  alert('triggered');
});
$('#bycategory').triggerHandler("click");
Elamurugan
  • 3,204
  • 13
  • 59
  • 104
-1

You have a spelling error. Please use:

{$("#anchor").trigger("click");});
Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42