-1

Quick question. I've got html code like that:

<li class='entry'>
    <div class='entryContent'>
        <p class='entryText'>Entry text></p>
        <a href="#" class='entryReply'>Reply</a>
    </div>
</li>

When I click on Reply a div with reply form is being appended to 'entry'. So it looks like:

<li class='entry'>
    <div class='entryContent'>
        <p class='entryText'>Entry text></p>
        <a href="#" class='entryReply'>Reply</a>
    </div>
    <div class='replyForm'>
        //form stuff
    </div>
</li>

Now what I want to do is to create user-script which will find that dynamic div.replyForm and append some stuff into it:

<li class='entry'>
    <div class='entryContent'>
        <p class='entryText'>Entry text></p>
        <a href="#" class='entryReply'>Reply</a>
    </div>
    <div class='replyForm'>
        //form stuff

        //MyAppendedStuff
    </div>
</li>

I've already tried

$("body").on("focus", ".replyForm", function(){ 
    $(this).append('<span>Hello World!</span>'); 
}); 

but it didn't work.

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Raff
  • 3
  • 1
  • Can you not just load the stuff into the div as you are creating it? Or add it to the HTML in the success callback of the ajax call? See [this](http://stackoverflow.com/questions/148361/how-can-i-give-keyboard-focus-to-a-div-and-attach-keyboard-event-handlers-to-it) related post. Unless you do something like make it `content-editable` or add a `tab-index` it doesn't look like keyboard centered events like `focus` will work... – War10ck May 23 '14 at 20:20
  • Well, the self creating div isn't mine. It's on the page code already. I just want to create a userscript which will add some more code to dynamically created one. I will have a closer look on your related post. Many thanks! – Raff May 23 '14 at 21:13

1 Answers1

0

You are creating a focus listener for div.replyForm. You probably want to bind the listener to the form inputs, instead. Something like this:

$('body').on("focus", "div.replyForm input", function () {
    $('div.replyForm').append('<span>Hello World!</span>');
});

Working Example (jsfiddle)

showdev
  • 28,454
  • 37
  • 55
  • 73
  • well, it works for a content which is already there. But what if we load the .replyForm after the page load or after on click event? – Raff May 23 '14 at 21:10
  • If you use a [delegated event](http://api.jquery.com/on/#direct-and-delegated-events) (as shown above), then the selector will find dynamically generated elements. Of course, this depends on the specific HTML structure that you generate. – showdev May 23 '14 at 21:18
  • Hi again. I have no idea why but it worked this time (even without input). Thank you for your help! – Raff May 25 '14 at 18:17