Search code examples
javascriptjqueryfocusjquery-click-eventjquery-focusout

Focusout if not elements is clicked (see fiddle)


I have an "clear"-icon dynamically showing up in my input-field when I write something. Keypress and focus events handle that well, the only thing is that I want the icon to be removed when the input field is not in focus mode. The problem is that I have a click event on the icon, so if I click the icon, the focusout-event fires. I can't figure it out.

$(".searchInput").focusout(function(e) {
    console.log(e);

    if(e.currentTarget != this) {
        if ($(".keypress").length > 0) {
            $(".keypress").remove();
        }
    }
})

I've put together a little fiddle: http://jsfiddle.net/w9RbW/.

As you can see, if the input value isn't empty, the icon is still there, I don't know how to check if it's being clicked, or something like that...


Solution

  • The problem (as you know) is that the clear icon is getting removed before its click event is fired when you focus-out from the text-box. One possible solution is altering the opacity of the clear icon instead of removing it, so that it still continues to receive events.

    Demo: http://jsfiddle.net/w9RbW/10/

    // Have the clear icon in there all the time
    $("<span class='keypress'><i class='icon-remove-sign'></i></span>").appendTo($(".searchInput").parent()); 
    
    $(".keypress").click(function(e) {
      if($(this).css('opacity') == 0) return;
      $(".searchInput").val("").focus();
      $(this).css('opacity', '0'); // hide it after clearing the text
    })
    
    // focusout
    $(".searchInput").blur(function(e) {
      $(".keypress").css('opacity', '0'); // hide it on blur
    })
    
    $(".searchInput").focus(function() {
      if ($(".searchInput").val() != "") {
        $(".keypress").css('opacity', '1'); // show it
      }
    })
    
    $(".searchInput").keyup(function() {
      if($(this).val() != "") {
        $(".keypress").css('opacity', '1');
      } else {
        $(".keypress").css('opacity', '0');
      }
    })