Search code examples
javascripteventsinlinestoppropagation

Stop event propagation for multiple inline functions JS


I have this type of code :

<button onclick="fn1();fn2();fn3()">Clic</button>

I test something in fn1 and if it is true, I don't want fn2 and fn3 to be called. I used event.stopPropagation() in fn1 (in a cross-browser manner and passing the event to the function) but the others functions are called anyway.

Can anyone help ?


Solution

  • try this:

    <html>
    <head>
      <script>
        function fn1() {
            alert('fn1()');
            return false;
        }
    
        function fn2() {
            alert('fn2()');
            return true;
        }
    
        function fn3() {
            alert('fn3()');
            window.location.assign("http://www.google.com");
        }
      </script>
    </head>
    <body>
        <button onclick="fn1()&&fn2()&&fn3()">Click</button>
    </body>
    </html>
    

    all functions should return boolean then use logical operators && inside onclick

    <button onclick="fn1()&&fn2()&&fn3()">Click</button>
    

    as you can see if the fn1() returns false f2() and f3() are not executed.