tags:

views:

766

answers:

6

when there is

<a href="javascript:onclick:alert('hi')"> click </a>.

how come $('a').click(); doesn't make the alert popup?

A: 

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.

meder
Are you referring to onclick also? What's wrong with onclick?
recursive
It's an inline event handler and it's a best practice to separate content from presentation, from behavior ( 3 legged stool of web design ).
meder
+2  A: 

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="#"

yoda
A: 

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.

Marius
A: 

I think this is what you want:

<a href="#" onclick="alert('hi')"> click </a>

Then, to trigger it manually:

$('a').trigger('click');
brianreavis
yes. how come it didn't work for me ?also when there actually is an href URL, why doesn't .trigger('click') make the browser navigate ?
Why can't you attach the event handler externally, as shown in yoda's and my answers? Inline event handlers are not recommended.
meder
meder, i need to literally "click" an element.for instance i did this$('a').trigger('click');<a href="http://google.com"> clickme</a>Nothing happened....
+1  A: 

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>
Guffa
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");
Justin