Grow your CSS skills. Land your dream job.

Coffeescript and rails popup only working on first object in array

  • # March 19, 2013 at 8:36 pm

    I have a products page listing several different products. When a products main image is clicked i would like a popup/lightbox to display with another image of that product and additional information.

    However, the click event is only working for the first product. Here’s my coffeescript:

    $(document).ready ->
    i = $(“.main-image”).attr(“data-productid”)
    button = $(“#single_” + i)
    button.on “click”, ->
    $(“#product_popup”).show()

    And my html/erb:

    < % products.each do |product| %>
    < % if product.on_display? %>

  • “classes”) %>” data-hook=”products_list_item” itemscope itemtype=”http://schema.org/Product”>
    < %= large_image(product, :itemprop => “image”, :class => “product-image”) %>

    Thank you very much!

# March 19, 2013 at 11:11 pm

One solution would be to iterate through each product, and create a button based on the product id.

Your code assigns a constant to the i variable

i = $(“.main-image”).attr(“data-productid”)
button = $(“#single_” + i)

This code will only create one button.

One way of iterating through each product would be to get all the .main-image class objects, then use the .each() function

i = $(“.main-image”)
i.each ->

It also looks like you will have multiple dom elements with the id of #product_popup

I made a codepen based on the code you posted.
It should be helpful, please ask questions.

http://codepen.io/jessecfisher/pen/DdiHn

# March 19, 2013 at 11:25 pm

Thank you for your help! How about this for the coffeescript:

jQuery ->
$(“.main-image”).each () ->
i = $(this).attr(“data-productid”)
$(“#single_” + i).on “click”, ->
$(“#product_popup”).show()

This at least gets all the products clickable, but when you click them it still only brings up the the image of the first product. Does that have something to do with the multiple dom elements with the id of #product_popup?

# March 20, 2013 at 10:05 am

Ok, so I implemented your coffeescript:

$(document).ready ->
i = $(“.main-image”)
i.each ->
id = $(this).data(‘productid’)
button = $(“#single_” + id )
button.click ->
$(“#product_popup_” + id).fadeToggle()

And the html/erb:

  • “classes”) %>” data-hook=”products_list_item” itemscope itemtype=”http://schema.org/Product”>
    “>
    < %= large_image(product, :itemprop => “image”, :class => “product-image”) %>

    But its still only opening the popup for the first product. When you click the others nothing happens. I’m sure I’m just missing something. Thank you!

  • # March 20, 2013 at 10:53 am

    I got it! I needed to remove the position fixed on each image. Thanks so much. I really appreciate you taking the time to make the codepen. You’ve taught me a lot.

    Viewing 5 posts - 1 through 5 (of 5 total)

    You must be logged in to reply to this topic.

    *May or may not contain any actual "CSS" or "Tricks".