Shruti
Shruti

Reputation: 721

How to call custom jquery function onClick

Hi. I am new to jQuery.. I want to know how to call custom jQuery function by onClick attribute of HTML. This was the basic I was trying.Further I want to make parametrised function and want to call that function onClick attribute.

my jQuery function is:

jQuery.fn.myFadeIn=function() {
    return $('#fadeInDiv').fadeIn();
};

and the HTML is:

<input type="radio" name="contentCalls" class="radioButton" id="Calls" onclick="myFadeIn();">

<div id="fadeInDiv">
div to open
</div>

Thanks!

Upvotes: 11

Views: 46636

Answers (3)

cllpse
cllpse

Reputation: 21727

This plugin alert()s the ID of each matched element:

jQuery.fn.alertElementId = function()
{
    return this.each(function()
    {
        alert(this.id);
    });
};

And to use it:

// alert() each a-element's ID
$("a").click(function ()
{
    $(this).alertElementId();
});

Upvotes: 15

Quentin
Quentin

Reputation: 943569

Replace:

jQuery.fn.myFadeIn=function() { return $('#fadeInDiv').fadeIn(); };

With:

var myFadeIn=function() { return $('#fadeInDiv').fadeIn(); };

(Assuming you are running this in the global scope)

Upvotes: 6

David Andres
David Andres

Reputation: 31781

You need to assign this custom function to some element's click handler, as in:

$("#Calls").click($.myFadeIn);

What is important to note is that the function you have added to jQuery through its jQuery.fn syntax should be available as part of the $ or jQuery JavaScript objects.

Upvotes: 5

Related Questions