4
<div class='my_class'></div>
<div class='my_class'></div>
<div class='my_class'></div>
<div class='my_class'></div>

jQuery('.my_class').hide();
jQuery('.some_other_class').live('click', function(){
// some other stuff that puts in another div with class 'my_class'
});

With this script, the first 4 divs will be hidden on load. However, when I click whatever, the new div will not be. How do I make it so that all future elements matching 'my_class' are automatically hidden as well?

EDIT

I found this here:

$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;}
</style>").appendTo("head"); $("<div/>").addClass("redbold").text("SOME NEWTEXT").appendTo("body");

This is more along the lines of what I would use. Much dryer.

Community
  • 1
  • 1
awilkening
  • 1,062
  • 8
  • 26

3 Answers3

0

Use jQuery('.my_class').live('hide');

UPDATE: Could you just use CSS code to set display: none; for all my_class elements?

Ville Salonen
  • 2,654
  • 4
  • 29
  • 34
0

Basically, you'd want to ensure you've hidden the new element before it's rendered on your page:

jQuery('.my_class').hide();
jQuery('.some_other_class').live('click', function(){
   var myDiv = $('<div />', { "class": "my_class" }).hide().insertAfter('div.my_class:last');
});
Phil.Wheeler
  • 16,748
  • 10
  • 99
  • 155
  • I'm trying to keep this as dry as possible. I don't want to put that line in the 3 other scripts that also effect this page. – awilkening Aug 02 '11 at 05:28
0

Not sure if you can do what you're after automatically, but you could try something like this:

jQuery('.some_other_class').live('click', function(){
    var myClassIsVisible = $(.my_class).is(':visible');
    var newDiv = // create new div with class 'my_class'
    newDiv.toggle(myClassIsVisible);
    // insert newDiv into the DOM
});

This would create the new div in the same state as the existing ones.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116