How can I exit a click function or prevent the function from triggering until a condition is met

javascript stop function from another function
preventdefault
stoppropagation
how to prevent function call in javascript
javascript exit function if condition
javascript exit()
jquery stop function execution
stoppropagation not working

Goal: I want to be able to add comments onto images and use their X,Y coordinates to save the comment and display for later.

Expected Result: I want a user to click on a "New Comment" button which enables "Comment Mode" and displays a form. If a user clicks away from the form, I want the form to hide and "Comment Mode" to become disabled until the user clicks "New Comment" again. If "New Comment" is pressed again, repeat the above.

Actual Result: The snippet of code currently allows a user to click "New Comment". Once clicked the commentMode() function is triggered and listens for a click on the #imageWrapper. If the user clicks away, the form is hidden - but when I press "New Comment" again, the form remains hidden.

function commentMode() {
          imageWrapper.toggleClass('new-comment-pointer'); // changes cursor to show its active
          imageWrapper.click(function(e) { // on clicking the image
            newComment = !newComment; // newComment is true
            console.log(newComment);
            if(newComment) { // if newComment is true, show the form near the click
              getCoordinates(e, $('#imageWrapper'));
              form.show().css({'left': formX, 'top': formY});
              form.find('textarea').focus();
              form.find('#xAxis').val(x); // x is from the getCoordinates
              form.find('#yAxis').val(y); // y is from the getCoordinates
            } else { // if newComment is false, hide the form and turn stop imageWrapper.click
              form.hide();
              imageWrapper.removeClass('new-comment-pointer');
              newComment = !newComment;
              return; //stop listening for click
            }
            return; 
          });
        }

https://codepen.io/lachiekimber/pen/YzzPEqw

I do not know why everybody make it complicated. First give the form and the button a id. Then define a default form css class which is hidden.Define another ones which makes it visible some kind of:

<style>
  .invisible   {
    display:none;  
  }

.visible   {
    display:block !important;  
 }
</style>

Now we add a document listener which make things more simple instead fiddeling on whatever event...

document.addEventListener(" click ", function(event) {
//try to get a id even when the event element has not
// directly a id but maybee his parent the form
try {
   var id = event.target.id;
   if (id === "") {
      for (i = 0; i < event.path.length; i++) {
        id = event.path[i].id;
        if (id !== "") {
           if (id === "formid") {
            break;
           }
        }

    }
    } catch(ex){
       console.log(ex);
       return;
    } 
    var form=document.getElementById("formid");
    switch(id){
        case "showcommehtbuttonid":
        case "formid":
              form.classList.add("visible");
        break;
        default:
              form.classList.remove("visible"); 
    }
 }

The toggle state has a disadvantage in your case - complicate to handle. Works best by a simple id and button. There is no doubt about then. Adding and removing handlers also makes no real sense. Either the user clicks on the form or the button and the form becomes visible. Or he clicks something else. In this case no id or the "wrong" id will be chosen. In this case the default switch rule make the form invisible. The thing is untested and might need some minor tweaks. And best - in the event handler you can now also add very simple more actions.

In JavaScript, how do you stop a function when something happens , If you want to "sleep" or otherwise block execution, this is essentially If you want to simply exit a function, you can use "return" to return from the which exits every function until it is caught (if it all) with a try/catch statement. If you want to loop until some condition is. Actually it's not even about a whole function call. Exit Function can be used only inside a Function procedure. To specify a return value, you can assign the value to the function name on a line before the Exit Function statement. To assign the return value and exit the function in one statement, you can instead use the Return Statement. Exit Property.

As @Davo mentioned in the comments, I attempted to refactor the code. I started by cleaning up the code into functions and not nesting click events. Whilst refactoring, I used console.log's to help me identify when the commentMode was active - then triggered the showForm() or hideForm() functions. For a working example: https://codepen.io/lachiekimber/pen/bGGNYmK

$(function () {

        var imageWrapper = $('#imageWrapper');
        var form = $('.new-comment');
        var x, y, formX, formY;
        var newComment = true;
        var commentMode = false;

        $('#newComment').click(function() {
          imageWrapper.toggleClass('new-comment-pointer');
          commentMode = !commentMode;
          //console.log('newComment');
        });

        $('#imageWrapper').click(function(e) {
          if(commentMode) {
            //console.log('commentMode: true');
            showForm(e);
          } else {
            //console.log('commentMode: false');
            hideForm();
          }
        });

        function showForm(e) {
          getCoordinates(e, imageWrapper);
          form.show().css({'left': formX, 'top': formY});
          form.find('textarea').focus();
          form.find('#xAxis').val(x); // x is from the getCoordinates
          form.find('#yAxis').val(y); // y is from the getCoordinates
        }

        function hideForm() {
          form.hide();
        }

        function getCoordinates(e, image) {
          var offset = image.offset();
          x = e.pageX - offset.left;
          y = e.pageY - offset.top;
          formX = x + 50;
          formY = y + 20;
        }

});

The difference between 'return false;' and 'e.preventDefault();', Click on the inner box, a click will trigger on the outer box too, unless you prevent propagation. Like this: This demo. So in other words: function()  A fileUpload function to trigger the click event on the file upload input. Assigning both the dropzone div and a button to variables. Adding event listeners to those, which when clicked invoke the

Working and tested :) ! Ok we could work on the page style quite a bit but :d Look how simple the whole page looks also. I do not have to fight with jquery for this little task :) I set also the autofocus just by plain html.

            <!DOCTYPE HTML>

        <html>

            <head>
                <title>Untitled</title>
                <style>
                    .invisible {
                        display: none;
                        border: 1px solid red;
                    }

                    .visible {
                        display: block !important;
                    }
                </style>
            </head>

            <body>

                <form id="formid" class="invisible">
                    <h1>Form</h1>
                    <input type="text" name="size" autofocus>

                </form>

                <hr>
                <input type="button" value="click" id="showcommentbuttonid">
                <script>
                    document.addEventListener("click", function(event) {
                                 try {
                                    var id = event.target.id;
                                    if (id === "") {
                                        for (i = 0; i < event.path.length; i++) 
                                          {
                                            id = event.path[i].id;
                                            if (id !== "") {
                                                if (id === "formid") {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                } catch (ex) {
                                    console.log(ex);
                                    return;
                                }
                                var form = document.getElementById("formid");
                                switch (id) {
                                    case "showcommentbuttonid":
                                    case "formid":
                                        form.classList.add("visible");
                                        break;
                                    default:
                                        form.classList.remove("visible");
                                }

                            }
                            )
                </script>
            </body>

        </html>

event.stopImmediatePropagation(), To simply prevent the event from bubbling to ancestor elements but allow other Since the .live() method handles events once they have propagated to the top of the therefore, may prevent the delegated handler from triggering by calling event. <script>. $( "p" ).click(function( event ) {. event.​stopImmediatePropagation();. });. The next line is MsgBox “Exit Sub”: Image 1. VBA Exit Sub . As you can see, the ExitSub is exited right after Exit Sub command, so the MsgBox “The value of i is” & i will be never executed. Exit a Function in VBA. Exiting a function in VBA is similar to exiting a Sub, just the command is Exit Function.

Handling Events :: Eloquent JavaScript, Browsers do this by allowing us to register functions as handlers for specific events. <button>Click me any way you want</button> <script> let button = document. can call the stopPropagation method on the event object to prevent handlers For most types of events, the JavaScript event handlers are called before the  With useCallback, functions can fully participate in the data flow. We can say that if the function inputs changed, the function itself has changed, but if not, it stayed the same. Thanks to the granularity provided by useCallback, changes to props like props.fetchData can propagate down automatically.

The Golden Argosy, This curious procession lasted until the three called to mind the crooning of the his mind before the weapon reached his the three debouched from the woods glimpses of the possibilities within himself | before the missile could leave his uta for the method that had pre - abatement of earnestness , refused , and , for a  In addition to keeping any additional handlers on an element from being executed, this method also stops the bubbling by implicitly calling event.stopPropagation().To simply prevent the event from bubbling to ancestor elements but allow other event handlers to execute on the same element, we can use event.stopPropagation() instead.

How to exit a program or rather not process further code if a , How to exit a program or rather not process further code if a condition is not met ? Follow. 1,011 views (last 30 days). Tonu on 21 Nov 2012. Vote. 1. ⋮. Vote. 1. So, click on the Cancel button to close the userform, it will close the user form. #2 – Close UserForm Using Hide Method in Excel VBA. We can also close Userform using the “Hide” method as well in VBA. Now once again I will double click on the cancel button to see the private subprocedure.

Comments
  • the issue is, every time you click new comment you add another click handler to imageWrapper.click so you end up with that code running multiple times on each click
  • Actually, the problem is not that @Bravo, it's just that your else block is toggling the newComment value and then you're re-toggling that again in the begining of your onClick function.
  • @Bravo, is it bad that the code runs multiple times? Is there another solution that doesn't require it to fire multiple times?
  • @Davo, removing it allows it to be re-enabled. But now the form never goes away!
  • Yes Lachie, you need to refactor your code, it's not working with the right logic. The first thing is that you need to define the newComment variable outside the onclick function, as a global variable basic.
  • I do not know why i get downvoted- that will exactly do what he wants. His damn toggle state gets mixed up. And BTW: Ive not made this funny textarea which is a pain in the .... So i need at least a few trys or minutes to made it. But hey feel great !
  • I didn't downvote but I am confused about this. I currently show and hide the form successfully using JQuery hide() and show(). I agree my toggle state is complicated. Your code seems more complicated and I can't match that into what I've got?
  • it is not :) I just use plain javascript to add a global event listener. Then i know this listener is THERE ;) I add a for next loop over the bubbeling chain cause i do not know hat you has in the form. The user might click wherever. So in this case it runs the event chain up until it gets the form id. Than its happy. visible state is set even it might not be needed. If the user clicks wherever this chain will not work. So it becomes invisible. If the user clicks the button the same handler will also show this form. Thats not complicated thats stupid simple rocksolid :)
  • And also no Toggle state can get mixed up ;) There is no toggle. There is either on or off ;)
  • Try to get it mixed up ;)
  • Have you seen the CodePen at the bottom? codepen.io/lachiekimber/pen/YzzPEqw
  • Lachie i want to help (as a hobby or as a thank for the help i get here sometimes) - not do other peoples job for free :) Sure if you can afford 200 EUR per hour i might think about :) That is what my boss usually put on the bills. We are also really great on railroad bridges or concrete structures grin