Pez Cuckow
Pez Cuckow

Reputation: 14422

jQuery not behaving as expected in reference to clicks

I have an element that I grab the content of and swap for an input, I then want to user to be able to click on the input (to enter text as normal), but if they click anywhere else to swap it back to the text.

However the click event seems to fire even the very first time the user clicks anywhere on the page. My code is below, have I misunderstood something?

$(document).ready(function(){ 
   $("#thingy").css('cursor', 'pointer');
   $("#thingy").one("click", function() { 
     var element = $(this);
     element.css('cursor', 'auto');
     element.css('display', 'inline-block');
     element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100);
     $("#thingy").click(function() {
       return false;
     });    
     $(document).click(function() {
         alert("You clicked off the text-box");
         element.html(element.children('input:text').val());
     });
  }); 
}); 

Upvotes: 0

Views: 82

Answers (1)

Nick Craver
Nick Craver

Reputation: 630509

The reason it alerts even the first time is the first click handler (the .one() doesn't itself return false; or .stopPropgaton(), like this:

$(document).ready(function(){ 
   $("#thingy").css('cursor', 'pointer');
   $("#thingy").one("click", function() { 
     var element = $(this);
     element.css('cursor', 'auto');
     element.css('display', 'inline-block');
     element.fadeOut(100, function(){element.html('<input type="text" size="25" value="' + element.text() + '" style="width:' + element.width() + 'px;height:' + element.height() + 'px;border:none;padding:0px;margin:0px;">')}).fadeIn(100);
     $("#thingy").click(function() {
       return false;
     });    
     $(document).click(function() {
         alert("You clicked off the text-box");
         element.html(element.children('input:text').val());
     });
     return false;
  }); 
}); ​

You can test it out here.

A better approach would be to use the blur event instead, replacing this:

     $("#thingy").click(function() {
       return false;
     });    
     $(document).click(function() {
         alert("You clicked off the text-box");
         element.html(element.children('input:text').val());
     });
     return false;

With this:

     $(element).delegate("input", "blur", function() {
       element.html(element.children('input:text').val());
     });

You can try that version here.

Upvotes: 2

Related Questions