Question

I've been working through some tutorials to learn the basics of creating my own plugins.. But it doesn't seem to work.

What I'm trying to do is just create a basic slide toggle drop down (click once to display a div - click again to collapse it)

The content of the plugin I have:

$(document).ready(function () {

    (function ($) {
        $.fn.dropdown = function () {
            $.fn.dropdown = function () {
                this.preventDefault();
                $('.expanded').slideToggle(1000);
            }
            return this;
        };
    }(jQuery));
});

The HTML I have is:

<div class="Btn">Click Here</div>
<div class="expanded">
Here<br/>
Is<br/>
Some<br/>
Extra<br/>
Content<br/>
</div>

And to execute the plugin, I have:

$( ".Btn" ).click(function() {
dropdown();
});

If someone could assist me with where I'm going wrong, it would be appreciated.

Thanks

Was it helpful?

Solution

Check out this jsfiddle: http://jsfiddle.net/yvanavermaet/sc6Bw/1/

$( document ).ready(function() {
    $( ".Btn" ).click(function() {
        $(this).dropdown();
    });
});

(function( $ ) {
    $.fn.dropdown = function() {
        $('.expanded').slideToggle(1000);

        return this;
    };
}( jQuery ));

As some people have stated:

  • don't define $.fn.dropdown twice
  • don't define it in your document.ready (you should see it as a separate module)
  • use $(selector).dropdown();
  • e.preventDefault() doesn't have much effect on a div as it has no default.

Edit: By the way, try and follow 1 coding standard. When adding the click-event, you're using double quotes and when adding the slideToggle you're using single quotes. Aswell as with the spaces.

OTHER TIPS

To execute the plugin it should be:

$( ".Btn" ).click(function() {
    $(this).dropdown();
});

This is a cut down version that works.

A couple of things, for some reason you wrapped $.fn.dropdown inside $.fn.dropdown, not sure why but I removed it. Also jQuery functions don't work like regular javascript functions, they're need $(). before hand, as they're inside jQuery's scope. Finally this.preventDefault won't do anything in this context, as there isn't a default.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top