1

Problem: A function I am binding with a click event is firing off on bind.

I've found others with this same problem and found a couple of answers. However, on implementing those solutions, I am still seeing the same issue. I must be doing something wrong, but I can't seem to figure it out.

Demo of issue: https://jsfiddle.net/b35krwfh/16/

Original snippet of code (coffeescript) that was calling the function on bind:

$("body").bind "click", deviceCloseView

After some online research, I found the below as the recommended fix, but I'm still experiencing the same issue:

$("body").bind "click", ->
  deviceCloseView()

Update: it was suggested I remove the parenthesis, but that doesn't seem to fix the issue as it isn't executing at all when I do that:

$("body").bind "click", ->
  deviceCloseView

https://jsfiddle.net/b35krwfh/15/

Some references I used trying to fix this:

jQuery function called in a .bind click handler is running on document ready

Why does click event handler fire immediately upon page load?

Community
  • 1
  • 1
Nil
  • 99
  • 1
  • 1
  • 9
  • 1
    Can't seem to reproduce this. `$("body").bind "click", deviceCloseView` works as expected, as in it calls the function on "click". – Sergiu Paraschiv Mar 07 '16 at 16:40
  • Are you sure? I've made a jsfiddle demoing it with that and while deviceOpenView executes. deviceCloseView does not. https://jsfiddle.net/b35krwfh/12/ – Nil Mar 07 '16 at 17:11
  • You might want to engage in a little bit of debugging before asking for help, just a couple `console.log` calls (https://jsfiddle.net/ck51y35b/) will show that your code isn't doing what you expect it to. Clicking the image opens it and then immediately closes it. – mu is too short Mar 07 '16 at 17:26

2 Answers2

1

The deviceOpenView in your jsfiddle does not stop propagation of the click event. As you bind deviceCloseView to the body, it will get triggered by the same click as well.

You need to change deviceOpenView to stop the propagation of the click event to prevent this.

deviceOpenView = (event) ->
  event.stopPropagation();
  // ... your other code
Narigo
  • 2,979
  • 3
  • 20
  • 31
  • Ahh, I see, thanks a lot. Reading up more on propagation now, but that makes a lot of sense. Appreciated. – Nil Mar 07 '16 at 18:35
1

Your event is bubbling. Here is a fixed fiddle: https://jsfiddle.net/6nk3asfw/

Call preventDefault, stopPropagation, return false, I just did all of them :)

Some code:

deviceOpenView = (e) ->
    console.log("open");
    console.dir(e);
    e.preventDefault();
    e.stopPropagation();
aet
  • 7,192
  • 3
  • 27
  • 25