Reputation: 1313
I have a field in an HTML table in which the user can edit the values. When the user clicks one of the cells of that field, a textarea appears at this cell, the user edits whatever he wants and when he clicks outside of that textarea, it goes back to normal text. You know, standard stuff.
All of this is working properly with onfocus and onblur events, except for one thing : when I click inside the textarea (Ex.: I want to edit a certain part of the text by clicking between two letters), the onblur event is still called, thus closing the textarea, which is not what I want.
I'm having a hard time understanding why the event is called. Is this the phenomenon called event propagation I heard about? How can I work around or fix this behaviour?
Here's my code related to the situation (lightened a bit) :
Javascript
// Create a function that updates a table cell once the textarea loses focus (do not be confused with "losing its Ford Focus")
function createBlurFunction( cell, textArea, functionName ) {
return function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var result = JSON.parse(xmlhttp.responseText)[0];
/* Do stuff with AJAX result */
}
}
// Empty cell
cell.innerHTML = "";
// Send AJAX request
xmlhttp.open("GET","Some AJAX parameters", true);
xmlhttp.send();
}
}
// textArea is already defined somewhere else
textArea.addEventListener('blur', createBlurFunction( cell, textArea, cell.title ), false);
Thanks!
EDIT 1 :
I used a similar structure somewhere else in my web page (textarea that goes away when you click outside) and the behaviour is different : the textarea does not go away when I click inside of it.
However, I used Copy/Paste from the code above, so I might be suspecting a code error or something...
Upvotes: 0
Views: 1319
Reputation: 861
You could put the blur function on a timeout and in your focus listener clear the timeout.
var timer;
function createBlurFunction() {
var myFunc = function() { ... }
return function() {timer = setTimeout(myFunc(),300);};
}
function myFocusFunction() {
clearTimeout(timer);
//do stuff
}
Upvotes: 1