Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-attaching jQuery detach();

Tags:

jquery

I have detached a div and want to re-attach it when clicking on a button.

Here's the code:

$('#wrapper').detach();  $("#open_menu").click(function(){     ATTACH HERE !!! }); 

Any help will be appreciated.

like image 240
Jacques Goudreau Avatar asked Nov 23 '12 19:11

Jacques Goudreau


People also ask

What is jQuery detach?

jQuery detach() Method The detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events. This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.

What is difference between detach () and remove () method in jQuery?

remove() removes the matched elements from the DOM completely. detach() is like remove() , but keeps the stored data and events associated with the matched elements.


2 Answers

var el = $('#wrapper').detach();  $("#open_menu").click(function(){     $(this).append(el); }); 
like image 122
Asad Saeeduddin Avatar answered Sep 20 '22 21:09

Asad Saeeduddin


I needed a solution that would work even if there are other elements after the target element to detach and then reattach. This means that append may not be reliable because it would move that element back to the end of its parent. I had to use a placeholder which may not be the most elegant solution, but I haven't found another way..

var $wrapper = $('#wrapper')     , $placeholder = $('<span style="display: none;" />')         .insertAfter( $wrapper )     ; $wrapper.detach();  $("#open_menu").on('click',function(){     $wrapper.insertBefore( $placeholder );     $placeholder.remove(); }); 

To make this more reusable, it might be better to wrap it in a jQuery plugin:

(function($){      $.fn.detachTemp = function() {         this.data('dt_placeholder',$('<span style="display: none;" />')             .insertAfter( this ));         return this.detach();     }      $.fn.reattach = function() {         if(this.data('dt_placeholder')){             this.insertBefore( this.data('dt_placeholder') );             this.data('dt_placeholder').remove();             this.removeData('dt_placeholder');         }         else if(window.console && console.error)         console.error("Unable to reattach this element because its placeholder is not available.");         return this;     }  })(jQuery); 

Usage:

var $wrapper = $('#wrapper').detachTemp(); $("#open_menu").on('click',function(){     $wrapper.reattach(); }); 
like image 27
Femi Avatar answered Sep 20 '22 21:09

Femi