Question

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...

Was it helpful?

Solution 2

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');
  }
})

OTHER TIPS

See this http://jsfiddle.net/w9RbW/8/

If you only want to remove icon when not in focus.

    $(".searchInput").focusout(function(e) {
  $(".keypress").css('opacity', '0');
        if(e.currentTarget != this) {
            if ($(".keypress").length > 0) {
                $(".keypress").remove();
            }
        }
    })

why don't you set a timer for checking every 10 seconds whether 'clear' icon is there or not! Once you have found that textbox has lost focus, then you can remove that clear icon and stop that timer

Using jQuery to test if an input has focus

As workaround you can set/remove some flag on icon mouseover/out and check it in focusout event.

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