Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent blur() running when clicking a link in jQuery?

Tags:

jquery

i have:

<input type="text" /> 

and

$('input').blur(function(){     alert('stay focused!'); }); 

I want to prevent the blur function running when I'm "blurring" by clicking on an anchor element.

I.E. if i tab to another input, click somewhere on the page etc i want the blur to fire, but if i click a link, I don't want it to fire.

Is this easily achievable, or do i need to hack about with delegates and semaphores?

Thanks

like image 336
Andrew Bullock Avatar asked Oct 01 '11 17:10

Andrew Bullock


2 Answers

I had to solve this problem myself today, too. I found that the mousedown event fires before the blur event, so all you need to do is set a variable that indicates that a mousedown event occurred first, and then manage your blur event appropriately if so.

var mousedownHappened = false;  $('input').blur(function() {     if(mousedownHappened) // cancel the blur event     {         alert('stay focused!');         $('input').focus();         mousedownHappened = false;     }     else   // blur event is okay     {         // Do stuff...     } });  $('a').mousedown(function() {     mousedownHappened = true; }); 

Hope this helps you!!

like image 146
Alex B Avatar answered Nov 13 '22 14:11

Alex B


If you want to keep the cursor at its position in a contenteditable element, simply:

$('button').mousedown(function(){return false;}); 
like image 44
Jens Jensen Avatar answered Nov 13 '22 15:11

Jens Jensen