2

This is a rails 4.2 project using HAML

I'm looking to have a clickable image to trigger some functionality on click. I need to have accessible the image source.

rails view

- @gallery.pictures.each do |picture|
  = link_to image_tag(picture.image.url, class: 'thumb'), "#", class: "gallery_image"

JavaScript / jQuery

  $('.gallery_image').on('click', function() {
    event.preventDefault()
    console.log('This is a clickable image')

    // do something
  })

Right now, it works fine as a link. It redirects to, well... "#", but the console never shows this is a clickable image.

I know the javascript is accessed because if I add a typo, Google Chrome console immediately yells.

Any thoughts?

Thanks!

1 Answer 1

1
  • Wrap your jQuery into a DOM ready function
  • Use the event argument
  • Assign the click to your child .thumb

jQuery(function($) { // DOM ready and $ alias in scope

  $('.gallery_image').on('click', '.thumb', function(event) {
    event.preventDefault();
    console.log('This is a clickable image');

    // do something
  });

  // other DOM dependent code here

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

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.