Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind jQuery to ONE link <a> to an onclick function?

Tags:

jquery

How do I bind a function using jQuery to one and only one link label in my HTML document which has several links?

My code looks like this;

$("a").click(function(){
  $("#login").slidedown("slow");
});

But this binds all the links in the document.

like image 552
Gath Avatar asked Apr 03 '09 07:04

Gath


People also ask

Can you href a function?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

Can a link have an onclick?

This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.

What is the difference between bind () and live () method in jQuery?

In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.

Can we pass function in href?

The anwer is: not possible.


2 Answers

To expand on Michael, you'll want to add a return false;

$("#clicked_link").click(function(){
    $("#login").slidedown("slow");
    return false;
});

Otherwise when you click the link the browser will still attempt to follow the link and you'll lose the javascript action.

like image 114
Jeremy B. Avatar answered Sep 21 '22 09:09

Jeremy B.


Name your anchor/link that has the click event with an id attribute.

So for instance:

<a href="..." id="clicked_link">...</a>

And then use the following jquery statement:

$("#clicked_link").click(function(){ $("#login").slidedown("slow"); });

Easy as pie!

like image 28
Michael Avatar answered Sep 21 '22 09:09

Michael