1

I am designing a footnote at the bottom of an article to annotate following up status;

<article class="col-md-12">
</article>
<div class="col-md-12 footnote">
    <a href="{% url 'article:footnote_add'%}">add a footnote</a>
</div> 

When the "add a footnote" link is hidden after being clicked and prompt the "footnote form" which I set autofocus which textarea. The "autofucus" works properly.

$('.footnote-link a').on('click', function (e) {
    e.preventDefault();
    ...
    var $footnoteForm = $(`
<form class="article-footnote-form footnote-form" style="margin-top:10px" >
<div class="form-group row">
    <div class="col-md-9">
        <textarea class="form-control" name="footnote" rows="3" autofocus></textarea>
    </div>
    <div class="col-md-3">
        <button class="btn btn-primary" type="submit" id="articleFootnoteBtn">Add Annotation</button>
    </div>
</div>
</form>`);
     $articleFootnoteLink.parent().hide();
     $articleFootnoteLink.parent().after($footnoteForm);

The form is submitted to server using Ajax then I cleared the forms by

$footnotesTop.find(".footnote-form").html(""). Now the page displays the article and the newly added footnote.

However, if I click the "add footnote" again, it unable to get focus automatically as it does at first time until I refresh the page to click.

How could I get the form focus during the second click event.

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

1

You need to use a delegated eventHandler. The js code $('.footnote-link a').on('click', function (e) { is only applied to the elements jQuery finds using that selector when the page is loaded.

Try $( document ).on('click', '.footnote-link a', function (e) {. You can use a tighter selector rather than document - it seems like .footnote would work based on what I see.

jQuery delegated events tutorial

JasonB
  • 6,243
  • 2
  • 17
  • 27
  • Thank you, Is it a common practice always employed $(body) or $(document) rather than specified selectors? – AbstProcDo Jul 23 '18 at 04:06
  • No, not really. There could potentially be some lag for pages with a lot of dynamically added content and a lot of event handlers. If you have an inkling that you will be modifying the dom and you know there won't be a ton of elements on the page then the practice is okay. https://stackoverflow.com/questions/30922305/are-there-performance-drawbacks-to-using-a-delegated-event-handler-in-javascript – JasonB Jul 23 '18 at 04:12