views:

225

answers:

3

In HTML5, the search input type appears with a little X on the right that will clear the textbox (at least in Chrome, maybe others). Is there a way to detect when this X is clicked in javascript or jQuery other than, say, detecting when the box is clicked at all or doing some sort of location click-detecting (x-position/y-position)?

Thanks!

+1  A: 

It doesn't seem like you can access this in browser. The search input is a Webkit HTML wrapper for the Cocoa NSSearchField. The cancel button seems to be contained within the browser client code with no external reference available from the wrapper.

Sources:

Looks like you'll have to figure it out through mouse position on click with something like:

$('input[type=search]').bind('click', function(e) {
  var $earch = $(this);
  var offset = $earch.offset();

  if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
    // your code here
  }
});
mVChr
well, that sucks. maybe i'll go with plan B, which was run an event onClick if the input is now empty... maybe put it on a 25ms timer
Jason
@Jason yeah, and you can use the code I put above to only run it if the click occurred in the area where the X is. That in addition to checking if the input is empty like you said should suffice
mVChr
A: 

Actually, there is a "search" event that is fired whenever the user searches, or when the user clicks the "x". This is especially useful because it understands the "incremental" attribute.

Now, having said that, I'm not sure if you can tell the difference between clicking the "x" and searching, unless you use an "onclick" hack. Either way, hopefully this helps.

References:

http://help.dottoro.com/ljdvxmhr.php

Pauan
+1  A: 

Using Pauan's response, it's mostly possible. Ex.

<head>
    <script type="text/javascript">
        function OnSearch(input) {
            if(input.value == "") {
                alert("You either clicked the X or you searched for nothing.");
            }
            else {
                alert("You searched for " + input.value);
            }
        }
    </script>
</head>
<body>
    Please specify the text you want to find and press ENTER!
    <input type="search" name="search" onsearch="OnSearch(this)"/>
</body>
dosboy