Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Senior Coder
    Join Date
    Jun 2008
    New Jersey
    Thanked 259 Times in 256 Posts

    jQuery plugin: functions that trigger once

    Hopefully this is a straight forward question, unfortunately I can't seem to figure out what to google for it.

    If I'm making a plugin which contains a hook/function that's independent of the actual plugin assignment, is there some way to set it up so that hook isn't added each time the plugin is called?

    My terms might be off here, so a brief description. I'm making a simple plugin to create a css "select box" that takes a select box's data, makes a little HTML snippet, and then sets it up so when you click, it drops down, etc. So when I have

    jQuery.fn.prettySelect = function () {
    //Do code
    It'll attach to every select. That part is working fine.

    Now what I want to do is make it so if the options are open and someone clicks outside the options div, to close the options, which is a simple case of using $('html').click(function () {}); and stopPropogation (I think). However, I don't want to add that into the plugin as then it'll attach for every select I have. I'd prefer for it to hook once when prettySelect is loaded or hooked for the first time.

    Any advice? And if I'm using any terms improperly, please correct me so I can fix it for next time.

  • #2
    Regular Coder hdewantara's Avatar
    Join Date
    Aug 2009
    Jakarta, Indonesia.
    Thanked 52 Times in 51 Posts
    PHP Code:

    //where the install once function resides...
    var install_once null;

    fn.greenify = function(){

    //detect and do nothing if already installed...
    if (!install_once){
    install_once = function(){

    //for debugging purpose only...
    console.log('body click');

    //what the actual plugin would do to target elements...
    Something like above?
    Ref page: http://learn.jquery.com/plugins/basic-plugin-creation/

    I was probably in my laziest mood at the moment, sorry; so I have to make Ref page above as my test ground

    After running the above code via my FF's Scratchpad, I returned to the Ref page and run the following through my FF's Web-Console:
    1. $('.widget-title').greenify()
    2. $('.entry-title').greenify()

    Then whenever I clicked, anywhere, Web-Console reported it still as a one-click.

    Hope this helps a bit,
    Last edited by hdewantara; 09-15-2013 at 05:35 PM.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts