0

I just started learning about callback functions. Unfortunately I can't make this altered sample-code work.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready( function() {
    $(".closebtn").click(function(){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    });


    function function1(param, callback) {
        alert("Erste Funktion");
        callback();
    }

    function function2(param) {
        alert("Zweite Funktion");
    }
})

</script>

When I click on the button nothing happens. Can anyone help?

3
  • Add a button with the class closebtn and initialising the variable, this code works. What error are you getting? Commented Nov 21, 2018 at 15:29
  • 1
    You don't show the button so we can only guess that the button does not have the class name closebtn. Maybe you meant the id #closebtn? You should also get some errors since someVariable and someOtherVariable are undefined in the code shown. Commented Nov 21, 2018 at 15:29
  • 1
    We'd need to see a more complete example. Fundamentally, you're passing the callback into function1 correctly and calling it correctly. Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button; here's how to do one). Commented Nov 21, 2018 at 15:29

1 Answer 1

1

Your example works for me. Let me know what you think:

// these need to be defined
var someVariable = 'example value';
var someOtherVariable = 'example value';

$(document).ready(function() {
  $(".closebtn").click(function() {
    function1(someVariable, function() {
      function2(someOtherVariable);
    });
  });


  function function1(param, callback) {
    console.log("Erste Funktion");
    callback();
  }

  function function2(param) {
    console.log("Zweite Funktion");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="closebtn">Close</button>

Sign up to request clarification or add additional context in comments.

1 Comment

yes, it works, it was necessary to declare the variables. thank you!

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.