0

What's the cleanest way of executing something on an element that is dynamically loaded through js/jQuery? Basically the user adds a form that potentially has a wysiwyg editor in it (depending on the context); this is a textarea that needs to have something like $(".wysiwygTA").editor(); called on it. Of course I could do something like:

var newForm = 'some_form_loaded_via_ajax_with_a <textarea class="wysiwygTA"> in_it';
$(".formWrapper").append(newForm);
$(newForm).find(".wysiwygTA").each(function(){ $(this}.editor(); });

But that doesnt seem very clean to me. Ideally I want to do something in the fashion of

$(document).listenForAddedTextarea(function(textarea){textarea.edtior();});

So that I could add the form from multiple places. I could isolate the editor-invoke in a seperate function and just call that, but that still leaves me with an extra line of code each time I want to add an element.

So: what would be the best way around this? :o)

Best Regards,

Rasmus Dencker

rdiz
  • 6,136
  • 1
  • 29
  • 41
  • use on() bind dynamically. – SuperBear Sep 29 '14 at 08:21
  • @SuperBear - What would I bind it to? I tried on('[both load and ready]', '.wysiwygTA', ...), but neither works. – rdiz Sep 29 '14 at 08:23
  • So far the cleanest way I found is including (function(){$(".wysiwygTA").editor(); })(); in the HTML that is loaded via ajax. – rdiz Sep 29 '14 at 08:24
  • possible duplicate of [Event when element added to page](http://stackoverflow.com/questions/7434685/event-when-element-added-to-page) – Nagaraj Tantri Sep 29 '14 at 08:28

3 Answers3

0

Use Bind method for binding dynamically:

 $( document ).bind( "listenForAddedTextarea", function(textarea) {
 textarea.edtior();
 });
Hansraj
  • 174
  • 5
  • Thanks a bunch for your answer, but the listenForAddedTextarea is actually never triggered, it was just a kind of pseudo-alias for illustrating what I'm trying to achieve. – rdiz Sep 29 '14 at 08:22
0

There is no such thing as elementAdded event in JS. Your only option is the 1st one you mentioned. Adding scripts in HTML you are returning from the server is a bad idea IMO.

Dmitry
  • 6,716
  • 14
  • 37
  • 39
0

you can do one thing. Create an event and trigger that event whenever you want.

  1. Create an 'listenForAddedTextarea' event like
$(document).on("listenForAddedTextarea", function(textarea) {
 textarea.edtior();
});
  1. Trigger the event

$(document).trigger("listenForAddedTextarea");

Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
  • What is the point in creating and triggering an event that does not exist? He'll need to call `$(document).trigger("listenForAddedTextarea");` when he loads the HTML from the server. He can just call the function that adds the editor. – Dmitry Sep 29 '14 at 08:30
  • i just replaced this line $(newForm).find(".wysiwygTA").each(function(){ $(this}.editor(); }); from this line $(document).trigger("listenForAddedTextarea"); – Ankush Jain Sep 29 '14 at 08:35