james james - 7 months ago 37
Javascript Question

The way to callback a function

Here I'm trying to make both divs red, via the callback. However, it works only for one, not for both.

I know, it's probably not very clever question, but I really spend several hours trying to understand why it doesn't work.

What's wrong with it?

<div id="foo">foo</div>
<div id="bar">bar</div>


function foo() {
document.querySelector("#foo").style.color = "red";

function bar() {
document.querySelector("#bar").style.color = "red";




When you call foo(bar), it passes the function bar as an argument to foo. Yet foo doesn't list any arguments and you're not calling bar in it either. Change your foo function like so.

function foo(callback) {
    document.querySelector("#foo").style.color = "red";


This solution is not the best practice however for your situation. What you're trying to accomplish doesn't require a callback. You should do one of the following.

  • Combine these two functions into one.
  • Call foo and bar together.

You should avoid using a callback in such a simple case as this.