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?

3
  • 1
    Can't seem to reproduce this. $("body").bind "click", deviceCloseView works as expected, as in it calls the function on "click". Commented Mar 7, 2016 at 16:40
  • Are you sure? I've made a jsfiddle demoing it with that and while deviceOpenView executes. deviceCloseView does not. jsfiddle.net/b35krwfh/12 Commented Mar 7, 2016 at 17:11
  • You might want to engage in a little bit of debugging before asking for help, just a couple console.log calls (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. Commented Mar 7, 2016 at 17:26

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, I see, thanks a lot. Reading up more on propagation now, but that makes a lot of sense. Appreciated.
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();

1 Comment

That was it, thanks. I needed to do more reading on propagation.

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.