Skip to content Skip to sidebar Skip to footer

Stop Element From Disappearing When Clicked

I'm writing a simple jQuery plugin that will dynamically place a div under a text box whenever it has focus. I've been able to get the position just about right in all the browsers

Solution 1:

You are not going to be able to use the blur event if you want to place "clickable" elements in the div that shows. One way to solve this is to bind your event listener to a more global element like the document and then filter out the targets.

Here is a code sample:

$(document).on('click', function (e) {
      var targetEl = e.target,
          parent = $(e.target).parents()[0];
      if (relElem[0] === targetEl || self[0] === targetEl || self[0] === parent) {
          $(mainElem).show();
      } else {
          $(mainElem).hide();
      }
 });

Here is an update to your fiddle: http://jsfiddle.net/9YHKW/6/

Solution 2:

This is a fiddle that I threw together for a project a while back: http://jsfiddle.net/MYcZx/4/

While it is not based off of your fiddle (and I do apologize) I believe that the functionality is much the same as what you're looking for. My example does not include input fields, but rather spans that hold the values. And while I'm not managing focus/blur, you could add a tabIndex attribute to the spans and then add a trigger on focus that would open the menu.

var$sub = $('.subscription');

$sub
    .on('click', '.remove', function() {
        $(this).parent().remove();    
    })
    .on('click', 'li', function(e) {
        var$this = $(this),
            $parent = $this.parent(),
            $options = $parent.children('li'),
            $value = $parent.siblings('.value'),
            isMulti = $parent.hasClass('multi'),
            values = [];

        if(!isMulti) {
            $options.removeClass('active');            
        }

        $this.toggleClass('active');

        $options.filter('.active').each(function() {
            values.push($(this).text());
        });

        $value.text(values.join(', ') || 'select');

        $value[(values.length ? 'add' : 'remove') + 'Class']('set');
    });

var$clone = $sub.clone(true);

$('.new')
    .on('click', function() {
        $(this).before($clone.clone(true));
    });

Post a Comment for "Stop Element From Disappearing When Clicked"