smooth_smoothie
smooth_smoothie

Reputation: 1343

Javascript function not being called onblur

function close() {
  console.log('close');
  $("#display").hide();
}

I am trying to call a closefunction when the user clicks out of the input box, but it doesn't seem to be working.

Doesn't work:

<input type="text" name="searchQuery" id="searchQuery"  onblur="javascript: close();" onkeyup="javascript: getSuggest(); "/>

Works:

<input type="text" name="searchQuery" id="searchQuery"  onblur="javascript: alert('msg');" onkeyup="javascript: getSuggest(); "/>

getSuggest returns false if that's relevant.

Upvotes: 1

Views: 6002

Answers (6)

Anthony
Anthony

Reputation: 2411

Change the function name from close to something else since the close function is part of the window object.

Additionally your function declaration cannot be specified after any type of dom-ready event observers have fired.

Example: notice if you wait for window.load or dom.ready the function doesn't get attached to the dom element (input)

EDIT http://jsfiddle.net/bb84T/5/

Upvotes: 1

Jan Dragsbaek
Jan Dragsbaek

Reputation: 8101

You should use unobtrusive javascript instead, and inside your $(document).ready() add use the .blur function built in jQuery instead, like this:

$('#searchQuery').blur(function(){
    myClose();
});

You also need to rename your close function, because it is reserved according to mozilla docs (thanks to @Mike Stewart)

Upvotes: 1

u.k
u.k

Reputation: 3091

onblur is disabled on google chrome (this will work on firefox and IE) You can use

$('#searchQuery').bind('blur', close);

Upvotes: 0

Jake Feasel
Jake Feasel

Reputation: 16955

You don't need javascript: within your onblur. Change to this:

<input type="text" name="searchQuery" id="searchQuery"  onblur="close();" onkeyup="getSuggest(); "/>

edit Try changing to jQuery events instead of DOM events:

<input type="text" name="searchQuery" id="searchQuery">

<script>
$(function () {

  $("#searchQuery").on("blur", function () {
    console.log('close');
    $("#display").hide();
  });

});
</script>

Upvotes: 1

Shevchuk
Shevchuk

Reputation: 545

Do you really need onblur event in HTML? Maybe better attach jQuery 'blur' event to the element? Like this: http://jsfiddle.net/VaVy8/

Upvotes: 0

Joe
Joe

Reputation: 82614

close is a native function [docs]. You can't use that name. So

close(); is really window.close()

try:

<script>
function closse() {
  alert('close');
}
</script>
<input type="text" name="searchQuery" id="searchQuery" onfocus="closse();" "/>

Upvotes: 2

Related Questions