Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo ( ctrl + z ) functionality to bring back hidden divs

fiddle http://jsfiddle.net/Q8F5u/3/

I have multiple divs, each having a delete button on its top to delete that particular div(actually i have to hide not delete). After the divs have been deleted I want to retrieve them back by pressing CTRL + Z.

I have had some success in bringing them back. The Logic i have used is that i am pushing the deleted divs id's to a stack and whenever i am pressing ctrl + z, I am popping the last hidden div ID from the stack and using this id to bring back the hidden div.

Here the javascript:

var deletedBlocks = [];

$('.delete').on('click',function(){
   var deletedid = $(this).closest('div[id^=block]').attr('id');
    deletedBlocks.push(deletedid);
   $(this).closest('div[id^=block]').fadeOut(500); 


});

$('body').on('keydown',function(e){
    //check for ctrl + z key

    if( e.ctrlKey && e.which == 90){

        if(deletedBlocks.length > 0){

           var lastdeleted = deletedBlocks.pop();
            $('.container').children('#'+  lastdeleted).fadeIn(1000);
    }
        else{
            alert('NO further Shift to be retrieved');
        }
    }

});

The problem i am having is that in my real application there's no such unique id's for these divs. instead they all have same classes. How can i implement the same functionality without the div's having unique id's.

like image 592
bhavya_w Avatar asked Jun 13 '14 17:06

bhavya_w


2 Answers

If you are just hiding the divs you can actually push the div itself to the stack instead of an ID.

$('.delete').on('click',function(){
    var deleted = $(this).closest('div[id^=block]');
    deletedBlocks.push(deleted);
    deleted.fadeOut(500); 
});

$('body').on('keydown',function(e){
    //check for ctrl + z key

    if( e.ctrlKey && e.which == 90){

        if(deletedBlocks.length > 0){

           var lastdeleted = deletedBlocks.pop();
           lastdeleted.fadeIn(1000);
        }else{

            alert('NO further Shift to be retrieved');
        }
    }

});

Note, I just refactored your code. Didn't test it. But you get the idea and it should work.

like image 109
rescuecreative Avatar answered Oct 25 '22 13:10

rescuecreative


You might use jQuery's .eq() and .index() methods.

In your line:

var deletedid = $(this).closest('div[id^=block]').attr('id');

You might retrieve the index of the deleted element:

var deletedIndex = $(this).closest('div[id^=block]').index();

Store this index in your array and use .eq() later to undelete the correct element:

 $('.container').closest('div[id^=block]').eq(lastdeleted).fadeIn(1000);
like image 36
lfarroco Avatar answered Oct 25 '22 15:10

lfarroco