Tomarz
Tomarz

Reputation: 1097

jQuery how to reverse a remove() event

I have this code:

$(window).resize(function() {
        if($(window).height() < 768) {
            $('div#navigation ul li br').remove()
        } else {
}
    })

Is it possible to reverse the remove event on else? I need to have those
tags in the same place as before the action.

Upvotes: 4

Views: 8568

Answers (3)

Tomalak
Tomalak

Reputation: 338316

$(window).resize(function() {
  $('div#navigation ul li br').toggle( $(this).height() >= 768 );
});

.toggle() takes a Boolean parameter that defines whether the selected elements should be hidden (jQuery uses CSS display: none;) or shown.

In this case, window height is used to calculate the Boolean.


Premature optimization: If the above is sluggish for some reason, you could optimize it by selecting the breaks beforehand and remembering state to decide whether there is anything to do in the first place:

$(window).resize( (function () {
  var $window = $(window),
      $navigationBreaks = $('div#navigation ul li br'),
      prevState = isLargeWindow();

  function isLargeWindow() {
    return $window.height() >= 768;
  }

  return function () {
    var newState = isLargeWindow();

    if (newState == prevState) return;

    $navigationBreaks.toggle(newState);
    prevState = newState;
  };
})() );

This is a lot more code, a lot more complex and potentially a few milliseconds faster than the one-liner approach. Take it with a grain of salt.

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191779

There is no single method to "reattach" a DOM element in jQuery (or JavaScript in general). Instead what you have to do is either create a new element to attach later with the ususal append methods, or store the .removed / .detached element and then append that one later:

$br = $('div#navigation ul li br').remove();
//...
$('div#navigation ul li').append($br);

However, you can only .append, .prepend, .wrap, etc. You can't insert it back to where it was before if it was between other child elements unless you have some sort of placeholder, or you know the child element to insert before/after.

If your only reason for removing the element is to hide it, then you can use various show/hide methods to make it disappear visually without removing it from the DOM.

Upvotes: 0

Naftali
Naftali

Reputation: 146310

The best way to do that is use toggle (or hide and show) and not remove:

$(window).resize(function() {
    if($(window).height() < 768) {
        $('div#navigation ul li br').toggle();
    } else {
        $('div#navigation ul li br').toggle();
    }
});

Upvotes: 2

Related Questions