onclick - JQuery: Restore element content when clicked outside it -


there tons of questions on address issue of detecting clicks outside designated element. however, none of them seem serve purpose in scenario. here's function:

function rateit(){     var cell = $('td.ratingcell');     cell.dblclick(function(e){         e.preventdefault();         var oldhtml = $(this).html();// restore when clicked outside cell         var oldratingval = parsefloat($(this).find('span.ratingval:first').text(), 10);         var oldratingcount = parsefloat($(this).find('span.ratingcount:first').text(), 10);         var blanks = '<span id="5">☆</span><span id="4">☆</span><span id="3">☆</span><span id="2">☆</span><span id="1">☆</span>';         $(this).addclass('editablerating');         $(this).html("<span id='editrating'>" + blanks + "</span>");         var clickedstar = $('#editrating span');         clickedstar.click(function(f){             f.preventdefault();             var newrating = parsefloat($(this).attr('id'), 10);             var deckid = $(this).parent().parent().parent().find('td.ftable-deck-name:first').find('span.deck_id:first').text();             updaterating(deckid, newrating, this);         });     }); } 

basically, function makes table cell editable user update information inline. works fine when user update something. however, need handle situations user double-clicks cell (element referenced var cell in function above) edit clicks elsewhere (outside cell) without update or presses esc key. when happens, need restore contents of cell var oldhtml.

almost answers have found on mention defining global click handler bound body tag. if that, how pass value of oldhtml handler outside function above?

you may searched lot how relates logic why didn't answer it, can try use data() like,

.....    e.preventdefault();    $('table#tableid').data('oldhtml',$(this).html()); // restore when clicked outside cell ..... 

now when clicking outside cell need oldhtml table id like,

$(document).on('click',function(e){     var $elem = $(e.target);      if((!$elem.hasclass('ratingcell') && // if not td           !$elem.closest('td').hasclass('ratingcell')))// , not content     {         $td=$(elem).hasclass('ratingcell') ? $elem : $elem.closest('td.ratingcell'); // td         if($('table#tableid').data('oldhtml')){             $td.html($('table#tableid').data('oldhtml'));// set old content         }     } }); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -