0

I have a page where newly created Choices are appended to the list with some ajax code, so the user don't have to refresh the entire page. The list contains of 2 columns, where the column on the right have to have a css class called "ending", which makes sure it's floated to the right and the padding is zero on the right side as well.

The problem is that when a new Choice is appended the partial which is rendered is exspecting multiple Choices if the cycle function should work.

Please see my code below and let me know if you have any suggestions to how the code should be altered so the partial inserts the correct css class.

PARTIAL:

<% @tickets.each do |choice| %>
    <div id="<%= choice.id %>" class="<%= cycle("ticket shadow", "ticket shadow ending") %>" data-time="<%= choice.created_at.to_i %>">
<% end %>

AJAX in VIEW

<script type="text/javascript">
    var pusher = new Pusher('<%= Pusher.key %>'); // Replace with your app key
    var channel = pusher.subscribe('choices');

    channel.bind('created', function(data) {
        var after = $('.ticket:last').attr('data-time');

        var settings = { after: after}
        $.ajax({
            url: '/Home/Index',
            type: 'POST',
            dataType: 'json',
            data: settings,
            success: function (data) {
                $("#tickets").append(data.html);
                }
          });
        }

    );
</script>

EDIT:

I tried out the below and that seems to work, but also seems a bit hacky.. anyone with a smoother solution?

if (css_end == "ticket shadow") {
  $(".ticket:last").addClass("ending");
}
Twiddr
  • 297
  • 1
  • 4
  • 18

1 Answers1

2

Depending on your targeted browser set, I'd suggest using CSS3 queries to target every other element.

.ticket:nth-child(2n+1) {
  float: right;
  padding-right: 0;
}

This won't work in IE8, but it'll work in just about every other major browser, and you don't have to write specific classes to the elements to get the right behavior. The nth-child selector will simply apply to every odd-numbered element.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137
  • See that is very smart, but would really like to find a solution that the IE browsers can handle.. Does it by the way work in IE9? – Twiddr Oct 20 '12 at 08:49
  • It works just fine in IE9. See http://stackoverflow.com/questions/8492121/ie8-nth-child-and-before for an IE8 hackaround. http://selectivizr.com/ is a polyfill for IE6-8, as well. – Chris Heald Oct 20 '12 at 21:04