TheLearner February 2016

JQuery: Restore element content when clicked outside it

There are tons of questions on SO that address the issue of detecting clicks outside a designated element. However, none of them seem to serve my purpose in this scenario. Here's a function:

function rateit(){
    var cell = $('td.ratingcell');
    cell.dblclick(function(e){
        e.preventDefault();
        var oldhtml = $(this).html();// restore this when clicked outside the 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, this function makes a table cell editable for the user to update information inline. It works fine when the user does update something. However, I need to also handle situations where the user double-clicks the cell (element referenced by var cell in the function above) to edit but then clicks elsewhere (outside the cell) without any update or presses the Esc key. When that happens, I need to restore the contents of cell to var oldhtml.

Almost all the answers I have found on SO mention defining a global click handler bound to the body tag. But if I do that, how will I pass the value of oldhtml to that handl

Answers


Rohan Kumar February 2016

You may searched a lot but this is some how relates to logic that why you didn't get any answer for it, you can try to use data() like,

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

now when clicking outside the cell you need to get the oldhtml from the table id like,

$(document).on('click',function(e){
    var $elem = $(e.target);

    if((!$elem.hasClass('ratingcell') && // if it is not the td itself
          !$elem.closest('td').hasClass('ratingcell')))// and not its content
    {
        $td=$(elem).hasClass('ratingcell') ? $elem : $elem.closest('td.ratingcell'); // get the td
        if($('table#tableId').data('oldhtml')){
            $td.html($('table#tableId').data('oldhtml'));// set old content
        }
    }
});

Post Status

Asked in February 2016
Viewed 1,609 times
Voted 7
Answered 1 times

Search




Leave an answer