jQuery append not inserting detached elements

2.8k views Asked by At

I can't seem to get append working for elements I am detaching with detach()

Basically what I want to do is remove some images from the DOM based on screen size (larger than 900px) and add them back (smaller than 900px). I am using enquire.js to handle the breakpoints but I am unable to properly implement the insertion of the removed elements.

Here's the html:

<div class="mobile-slides">
  <a><img src="image.jpg" /></a>
  <a><img src="image2.jpg" /></a>
  <a><img src="image2.jpg" /></a>
</div>      

Here's the js I'm using:

enquire.register("screen and (min-width: 900px)", {
    match : function() {
        var slides = $('.mobile-slides a').detach();
    },
    unmatch : function() {
        $('.mobile-slides').append(slides);
    }
});

Detach seems to be working but when the second condition is met nothing is happening. Am I doing something wrong?

EDIT Stupid mistake on my behalf I was only declaring the variable "slides" inside the enquire match function therefore it wasn't available to the unmatch function.

This now works:

var slides = $('.mobile-slides a');
enquire.register("screen and (min-width: 900px)", {
    match : function() {
        $('.mobile-slides a').detach();
    },
    unmatch : function() {
        $('.mobile-slides').append(slides);
    }
});

I could also use remove() it seems instead of detach()

1

There are 1 answers

1
Janith Chinthana On
slides.appendTo( '.mobile-slides' );

sample code for button click ,

var slides;
$( "button" ).click(function() {
  if ( slides ) {
    slides.appendTo( ".mobile-slides" );
    slides = null;
  } else {
    slides = $('.mobile-slides a').detach();
  }
});