1

So, I'm working on a webpage that has a small "notepad" widget, and I've updated the interface to work as follows:

  1. The notepad is actually just a styled <ul> with each line on the notepad page as its own <li>.
  2. The user can simply click and type to add a new <li> because it is contenteditable: true.
  3. Each newly added line is placed in a <p> element, and styled with jQuery.

Now here's my jQuery issue... The code below successfully adds the "strikethrough" class to the <p> element when double-clicked, and then removes it when double-clicked again. HOWEVER, if I click the "notepad" to add a new <p> element, the jQuery script below doesn't work. It only applies to <p> elements that were already on the page when the document loaded the first time.

// NOTEPAD INTERFACE
$(".paper p").dblclick( function() {
  $(this).toggleClass("strikethrough");
});

Does anybody know how to make the same jQuery apply to every <p> element equally, regardless of when it was added to the DOM?

elersong
  • 646
  • 2
  • 11
  • 25
  • 1
    search for event delegation in jQuery. You have to use `$('.paper').on('dblclick', 'p',function(){...})` instead. – King King May 21 '14 at 17:47
  • 1
    @KingKing, That did it! If you'll submit that as an answer, I'll accept it gratefully! – elersong May 21 '14 at 17:50

1 Answers1

2

You need to use .delegate(). This will make your function be applied to every element, even the newly created ones:

$(".paper").delegate('p', 'dblclick', function() {
  $(this).toggleClass("strikethrough");
});

Here's the documentation for delegate

William Barbosa
  • 4,876
  • 2
  • 17
  • 36
  • So what's the difference between your `.delegate()` solution and @KingKing 's `.on()` solution? – elersong May 21 '14 at 17:51
  • One is more backwards compatible than the other, however if you're not building plugins that is irrelevant. – Kevin B May 21 '14 at 17:52
  • 1
    @elersong `.on()` is the new stuff added as of jquery 1.7 (and replacing `delegate`), you can freely use it if you use jquery 1.7 (or above). of course this answer is also correct, so feel free to accept it, I won't add my own answer. – King King May 21 '14 at 17:54
  • Exactly, it all comes down to backward compatibility – William Barbosa May 21 '14 at 17:56