1

I'm creating a jQuery plugin that allows me to easily display a popup. In this case, the trigger element is an input and the target element is a div. So, the functionality is based on the focus and blur event. When the input gets focus, the popup opens and when it gets blur, the popup closes. I need the popup to stay open when I click on it and it closes because of the blur event I have set. I have tried to plug in the jQuery off() function into my custom blur() function within the plugin but it doesn't work.

I want to be able to click inside the popup without closing it, even when the input is on blur state or if someone can provide me with a better approach with in the plugin, that will be great too!

JS code

    /*
 * Popbox plugin
 */

 $.fn.adPopbox = function(target){      
      return this.each( function() {
          var enabler = $(this)

              function focus() {               
                 return enabler.focus( function(){                           
                             target.addClass('triggered');                                                           
                        });
              }

              function blur() {                     
                 return enabler.blur( function(){                          
                            target.removeClass('triggered');                         
                        });
              }   

              function popbox() {
                 return target.click( function(){                      
                            target.addClass('triggered');       
                        });
              }

          focus();
          blur();
          popbox();

      });         
  }


/*
 * Invoke Popbox plugin
 */

    $(".popover-trigger").adPopbox($('.popover'));

HTML code

<div class="input-wrapper">
   <input type="text" class="popover-trigger">
</div>

<div class="popover">
   <p>Content to be showed!</p>
</div>

Here is a preview

Bharata
  • 13,509
  • 6
  • 36
  • 50
jQueryster
  • 171
  • 1
  • 4
  • 14

1 Answers1

1

You can not use the event blur because when you click outside the input, it is first the blur event that is triggered and then the event click but at that moment, your popup is already hidden and the target is on what is below, ie the body.

You should also use the click event on the document to close the popup by inspiring you with this answer: https://stackoverflow.com/a/3028037/4864628

Bharata
  • 13,509
  • 6
  • 36
  • 50
Alex83690
  • 758
  • 9
  • 30
  • 1
    I guess I'll remove the blur event and see what will work best and I'll check your suggested answer. Thanks! – jQueryster Jan 14 '18 at 20:58