Horacio
Horacio

Reputation: 1964

jQuery not detecting link on click

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!

Upvotes: 2

Views: 42

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206024

  • 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

}); 

Upvotes: 1

Related Questions