Phillip Senn
Phillip Senn

Reputation: 47625

jQuery fn namespace

I'm reading about the jQuery $.fn namespace, and in order to understand what I'm reading, I would like an example of a complete command if no shortcuts were taken. For instance,

$('p').click(function() {
console.log('click');
});

Could this be rewritten with .fn in it somewhere? What would be the exhaustive syntax?

jQuery('p',document).fn.click(function() {
window.console.log('click');
});

Upvotes: 6

Views: 3394

Answers (2)

Michael Buen
Michael Buen

Reputation: 39393

jQuery's fn is sort of like C#'s extension methods. For example, jQuery doesn't have built-in function for toggling the hiding and showing of element, however, you can build one yourself using fn. An example:

<head>
<script src="jquery-1.4.4.js"></script>


<script type="text/javascript">    
    $(function() {     
        var toggle = true;

        $("a").click(function() {        
            $("p.neat").showIt(toggle,"fast");    
            toggle = !toggle;
            return false;
        });

        $.fn.showIt = function(b,param) { 
            if (b) 
                $(this).hide(param);
            else     
                $(this).show(param);
        };


    });

    $("p.neat").hide();   
</script>

</head>

<body>

 <p class="neat" style="width: 200">
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 </p>

 <a href="/">Yeah</a> 
</body>

Sourced from: http://www.ienablemuch.com/2010/06/first-foray-to-jquery.html

Upvotes: 4

SLaks
SLaks

Reputation: 887489

jQuery.fn is an alias for jQuery.prototype; it's the standard Javascript prototype mechanism.
Actual jQuery objects (instances) do not have an fn property.

You need to call the functions such that the this keyword is the object you're invoking them on, using call or apply.

For example:

jQuery.fn.click.call(jQuery('p',document), function() { ... })

Upvotes: 5

Related Questions