1

In a Rails 3.2 app I have a coffeescript function that toggles a css class when a link is clicked.

#coffeescript
jQuery ->
  $(".toggle-link").click ->
    $(this).toggleClass "selected"

#view
<%= link_to "toggle", my_path, class: "toggle-link" %>

This works fine.

But if I move the link into an ajaxified partial, e.g. for pagination, the jquery toggle stops working.

Why is this?

And how can it be fixed?

2 Answers 2

5

You need to use on for dynamic elements :

jQuery ->
  $(document).on 'click', ".toggle-link", ->
    $(this).toggleClass "selected"

(replace document with the container of your pages for better efficiency)

Sign up to request clarification or add additional context in comments.

Comments

0

Use jQuery delegate function istead of click. http://api.jquery.com/delegate/

$('#paren-element-id').delegate('.toggle-link', click', function yourCallback(){});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.