0

Can someone tell me why this code is not hiding elements dynamically added to the html document:

$("p , h1 , h2").mousedown(function(){
    $(this).hide();
});

This selection works only with the existing element in the html page, but doesn't work with what I add with after method on the fly. It seems that any new p element or h1 element that get added in the fly doesn't get any recognition from this selector.

guest271314
  • 1
  • 15
  • 104
  • 177
kairox
  • 3
  • 1
  • 2
    Tried delegating from `document` `$(document).on("mousedown", "p, h1, h2", fn)` ? – guest271314 May 10 '15 at 15:03
  • yes think's it work very good like document get tracking of any new element that get added unlike my previous selector.at least that's what i think happen think's again. – kairox May 10 '15 at 15:12
  • @kairox Delegation use the fact that most event bubbles through the DOM as mousedown, but not all – A. Wolff May 10 '15 at 15:20

2 Answers2

0

Try delegating event from document

$(document).on("mousedown", "p, h1, h2", function() {
  $(this).hide();
});
guest271314
  • 1
  • 15
  • 104
  • 177
0

As for jQuery 1.7, this is the way to delegate event:

$(document).on("mousedown", "p , h1 , h2", function(){
    $(this).hide();
});

document or closest static container.

-DOC-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155