when there is
<a href="javascript:onclick:alert('hi')"> click </a>.
how come $('a').click();
doesn't make the alert popup?
when there is
<a href="javascript:onclick:alert('hi')"> click </a>.
how come $('a').click();
doesn't make the alert popup?
The reason it doesn't work is because you're not attaching the click event properly, you're hacking it in by throwing it inside the href value. Make it link to # or the real url, don't ever place JS inline. Then attach the event handler externally:
$('a').click(function(e) {
e.preventDefault()
alert('hi')'
});
Then trigger with .trigger('click')
if you need to do it manually.
Hi,
Wether you use normal javascript in the anchor or use jquery. If you want to use jquery, do this :
$('a').click(function (e) {
e.preventDefault();
alert('hi');
});
.. and remove the code you have inside href="" to something else, like a href="#"
The problem is your href code. There are two ways to make a link call a javascript function when a user clicks on it:
<a href="javascript:alert('hi');">click</a>
<a href="" onclick="alert('hi');">click</a>
Now you can use the jquery code to click on the link.
I think this is what you want:
<a href="#" onclick="alert('hi')"> click </a>
Then, to trigger it manually:
$('a').trigger('click');
The reason that you can't trigger the click event is that you are not setting any click event.
The onclick:
that you have in the code has nothing to do with the onclick
event, it's just a label. Naming it the same as an event doesn't make anything special happen.
So, your code is equivalent to:
<a href="javascript:alert('hi')"> click </a>
If you want an event, you use the onclick attribute:
<a href="somepage.html" onclick="alert('hi');"> click </a>
There is a way to make the click trigger work with href. You have to bind a window.location call using the event target to the click event. This will cause any onclick actions to be triggered, followed by the href target. Like so:
$("a").click(function(event) {
window.location = event.target.href;
});
$("a").trigger("click");