10 October, 2012

jQuery problem with simultaneous events

I was working on some jQuery validation logic in my project when I came across this problem. When two continuous events fired from jQuery or jQuery mobile i.e. focus () and select () or blur () and click () only one event get fired and other one not. This is very annoying problem which sometime force you to scratch your head for hours and days. I was also having same problem in one of my module where blur and click are called sequentially. I am not sure that this also happen with the traditional java script or not.

Scenario



I have two controls a textbox and a button A textbox has blur event and a button has click event. Now if you write something in textbox and click the button directly only blur event get fired but click event don’t. The ideal condition should be that first blur should called and then click. so now if your form has to get post on button click or some other logic written on its click

<input type="text" id="text1">
<br/>
<input type="button" id="btn" value="click">

$("#btn").click(function({
    alert("click")
})
$("#text1").blur(function({
    alert("blur")
})

Solution



Well you can say that it is not a proper solution but just a fix to achieve what is expected but this is the best what came out after hours of efforts and brain exercise. We have to capture the condition that button has been clicked, before blur event get fired. Mousedown is the best event we can use for this. so need to take a variable to set it true on button mousedown and in blur event we can check if the variable is true or not i.e. the button is also clicked or it is just a simple blur triggered in result of lost focus from text box. And there we can explicitly call the button click.

var clickwithblur false;

$("#btn").click(function({
    alert("click")
}).mousedown(function({
    clickwithblur true;
})
$("#text1").blur(function({
    alert("blur")
    if (clickwithblur{
        $("#btn").click()
    }
})



Fiddle Link


http://jsfiddle.net/amitrdx/TmPtZ

0 comments: