Richlewis
Richlewis

Reputation: 15374

Apply CSS to dynamically generated elements

I am trying to work out how to call my .each() function with a $(document).ready and a click event, at the moment I have this

$(document).ready(function(){
  $(".help-inline").each(function() {
    $(this).css('display', 'none');
  });
});

Within a form of mine using nested_form I can clone a field clicking '.example_button' and would like to apply the display:none rule to the newly created element within my DOM.

I have tried this, but obviously the rule is only applied when i click the '.examnple_button'

$(document).on('click', '.example_button', function(){
   $(".help-inline").each(function() {
     $(this).css('display', 'none');
   });
});

How can i apply the css rules under both circumstance?

Thanks

Upvotes: 0

Views: 206

Answers (2)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

You can try this :

$(document).on('focus', '.example_button', function(){
   $(".help-inline").css('display', 'none'); //or $(".help-inline").hide();
});

The .each() which you are using to iterate '.help-inline' is not required ,jquery will automatically iterate all elements with class help-inline in DOM.

OR

As far i understand your question you are cloning a field clicking '.example_button' then one thing you can do is that hide the element when you are creating it otherwise there must be a event on which you want to hide '.help-inline' elements,use that event with .on() and hide elements with class 'help-inline' inside DOM.

Upvotes: 2

Shai
Shai

Reputation: 7317

Break the common code out into a function, and call it in both instances.

function hideAllTheInlineHelps() {
    $('.help-inline').hide(); // or .css('display', 'none')
}

$(document).ready(function() {
    hideAllTheInlineHelps();
});

$(document).on('click', '.example_button', function() {
    hideAllTheInlineHelps();
});

Update

Thanks to @Kartikeya for pointing out that you want the function to run without clicking the button.

Looking at the docs for "nested_form", it seems you can react to the nested:fieldAdded event:

$(document).on('nested:fieldAdded', function(evt) {
    hideAllTheInlineHelps();
    // or $('.help-inline').hide();
});

Upvotes: 1

Related Questions