Question

My app has something called "memos". And you can reply to other memos using @ tags inside your memo. For example:

Hi this is a reply to @123

Then, if you click, @123, then memo #123 is rendered underneath the memo you're viewing.

_memo.html.erb:

<div class="memo">
    <div class="memo-content">
        <%= raw simple_format(memo.content).gsub(/@([a-z0-9A-Z]+)/, '<a  data-remote="true" class="marker" href="/memos/\1">@\1</a>')%>
    </div>
</div>

app/assets/javascripts/memo.js:

$(function() {
    $(".marker").on("ajax:success", function(e, content){
        console.log("hi")
        $(".memos-container").append(content);
    });
})

memos_controller.rb:

  def show
    @memo = Memo.find(params[:id])
    if request.xhr?
      render partial: "shared/memo", locals: { memo: @memo } 
    end
  end

The first click works fine. If I click on @123, then memo #123 is rendered in the page. If I click on any other @ tags inside that first memo, they all work too.

Problem is, nothing inside that rendered memo is clickable. So if memo #123 also has an @456 tag, and I click on it, nothing is rendered.

Looking at my Network console in Chrome, it is making the get request, only the jQuery is not acting on those newly rendered DOM elements.

I've looked at similar questions on SO, and they all say use .on, which, as far as I can tell is what I'm doing. But I'm a total Javascript newb.

Was it helpful?

Solution

I got it to work by using this:

$(function() {
    $(document).ajaxSuccess(function(e, content){
        console.log(content.responseText)
        $(".memos-container").append(content.responseText);
    });
})

But if there's a better way to do this I'm open to suggestions :)

Now turbolinks is making it act all wonky. But That's a different topic...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top