jQuery how to reverse a remove() event

jquery, reverse

Solution

$(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.

Problem

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.

Original source