1

I have a set of elements:

<a class="post-thumb" href="http://google.com">
  <img src="http://placehold.it/100x100" alt="" />
</a>

<a class="post-thumb" href="http://google.com">
  <img src="http://placehold.it/100x100" alt="" />
</a>

<a class="post-thumb" href="http://google.com">
  <img src="http://placehold.it/100x100" alt="" />
</a>

When a .post-thumb element is clicked it should add a class of post-thumb--active to itself and not fire the link, when the element is clicked again it should go to it's link as per normal. If the page is scrolled then all .post-thumb elements should go back to their original state.

The jQuery code I'm using at the minute is:

var $postThumb = $('.post-thumb'),
    $postThumbStoredClick;

$postThumb.on('click', function() {

  $(this).addClass('post-thumb--active');

  $postThumbStoredClick = $postThumb.data('events').click[0].handler;

  $(this).unbind('click');

  return false;

});

$(window).scroll(function() {

  $postThumb.removeClass('post-thumb--active');

  $postThumb.bind('click', $postThumbStoredClick);

});

This doesn't work 100%, for example if you click a .post-thumb element then click the one next to it then it fires the link, this shouldn't happen.

If anyone could help at all that'd be sweet as this is driving me crazy.

Tom
  • 795
  • 1
  • 8
  • 21

1 Answers1

2

Just return from the click event handler if the element has the class post-thumb--active.

$postThumb.on('click', function() {
    if ($(this).hasClass("post-thumb--active")) return;
    $(this).addClass('post-thumb--active');
    $postThumbStoredClick = $postThumb.data('events').click[0].handler;
    return false;
});

and change the window scroll handler to this...

$(window).scroll(function() {
    $postThumb.removeClass('post-thumb--active');
});

That way, you're not having to remove and reassign the event handler based on anything else.

Reinstate Monica Cellio
  • 24,939
  • 6
  • 47
  • 65