Undo (ctrl + z) to return hidden divs

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

I have several divs , each of which has a delete button , to remove this particular div (in fact, I have to hide, not delete). After the divs have been deleted , I want to return them by pressing CTRL + Z.

I had some success in returning. The logic I used is that I pushed the deleted divs id onto the stack , and whenever I press ctrl + z, I popping the last hidden div identifier from the stack and using that identifier to return the hidden div.

Here's 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 facing is that in my real application there is no such unique identifier for these divs. instead, they all have the same classes. How can I implement the same functionality if the div does not have unique identifiers.

+6
source share
2 answers

If you just hide divs, you can actually push the div itself onto the stack instead of 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'); } } }); 

Notice, I just reorganized your code. Did not check. But you get the idea, and it should work.

+5
source

You can use jQuery . eq () and . index () .

In your line:

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

You can get the index of the deleted item:

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

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

  $('.container').closest('div[id^=block]').eq(lastdeleted).fadeIn(1000); 
+1
source

Source: https://habr.com/ru/post/970809/


All Articles