Michael Schwartz
Michael Schwartz

Reputation: 8415

JQuery: Dynamically Remove Elements (Isolate Function)

fiddle - http://jsbin.com/oloriTo/1/edit

Removing elements isn't the problem, but when I click on the remove false button (class is .rf) I want to no longer remove elements, unless the remove true (class is .rt) button is clicked.

Currently when I click the remove true element it does as expected. (demos a bit crummy but it gets the point across) When I click on the remove false button I can still click on elements within the .container div and remove them, which is not suppose to happen.

Any help is greatly appreciated.

$(document).ready(function() {
  var enabled = false;
  $('.rt').click(function() {
    enabled = true;

    if (enabled === true) {
      $('.container *').on('mousedown touchstart', function() {
        $(this).remove();
        return false;
      });
    } else {
      enabled = false;
    }
  });

  $('.rf').click(function() {
    enabled = false;
  });
});

Upvotes: 0

Views: 54

Answers (1)

Malk
Malk

Reputation: 11983

You are binding the remove code inside the set enabled code. Break it out and have it look at the variable set by .rf and .rt.

$(document).ready(function() {
  var enabled = false;
  $('.rt').click(function() {
    enabled = true;
  });

  $('.rf').click(function() {
    enabled = false;
  });
  $('.container').on('mousedown touchstart', '*',function() {
      if (enabled)      
        $(this).remove();
      return false;
   });
});

Upvotes: 3

Related Questions