Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function as a parameter to an another function in JS?

I try to do something like this Javascript function as a parameter to another function?, but unfortunately I haven't succeeded. I've done something wrong, but I don't know what. Please help me!

There is a div-element and a function. What the function does is: takes an another function as a parameter and execute it on click on the div-element:

UPDATE3:
I've tried to get the code to work with your examples beneath, with my original web project. But I've got some problem with some parameters. I hope you can answer this question as fast as the others.

UPDATE4:
Thanks Andy E! and all other who have helped me! Really appreciate it!

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
  <head>

    
  </head>
  <body>
    <div id='divElement'>Hello World!</div>
    <script type="text/javascript">
        
        function button(exefunction){
            //Some code that decide which date
            var date = '20101010';
            document.getElementById('divElement').onclick = exefunction(date);
        }
        function testfunction(text){
            document.getElementById('divElement').innerHTML = text;
        }
        button(testfunction);
    </script>
  </body>
</html>
like image 375
einstein Avatar asked May 03 '26 05:05

einstein


2 Answers

change testfunction to function and you'll have an anonymous function that is passed as the argument. You also need to remove the parens from exefunction (with them the function is called instead of assigned):

    function button(exefunction){
        document.getElementById('divElement').onclick = exefunction;
    }
    button(function(){
        document.getElementById('divElement').innerHTML = 'Changed';
    });

Here is a working example to play around with.


Remove your parens!

    button(testfunction);
    // not button(testfunction());

The brackets execute the function instead of passing it as an argument. When you execute a function its return value is passed instead.

Second working demo.


For your last edit, you need to create another anonymous function for the code to work:

        document.getElementById('divElement').onclick = function () {
            exefunction(date);
        }

Third (final?) working demo.

like image 134
Andy E Avatar answered May 05 '26 18:05

Andy E


I would replace the line

button(testfunction());

by

button(testfunction);

UPDATED The point is that onclick expect an none argument functions yous should try something along the lines

 function button(exefunction){
        //Some code that decide which date
        var date = '20101010';
        document.getElementById('divElement').onclick = function() {exefunction(date);}
    }
like image 43
Xavier Combelle Avatar answered May 05 '26 17:05

Xavier Combelle