1

i try to pass paramater to function. When i click the div it will alert the paramater that i pass

i have 2 file

  • index.html
  • script.js

here's what i try

Example 1

index.html

<div id="thediv" >

script.js

window.onload = initialize;

    //bind event listener
        function initialize(){
             document.getElementById("thediv").onclick = myFunction(" something ");
        }
    //end of bind

    //function
        function myFunction(parameter) { alert( parameter ) };
    //end of all function
  • the trouble is the function its executed without click

Example 2

index.html

<div id="thediv" onclick="myfunction('something')" >

script.js

function myFunction(parameter) { alert( parameter ) };
  • yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
  • i want to separate my code into 3 section (similiar with example1)
    • the view(html element)
    • the element have which listener
    • the function

what should i do? or can i do this? (i don't want to use another library)

2
  • Did you include the .js file? If you put an alert in the script.js, does it pop up? Commented Nov 21, 2013 at 10:14
  • yes. i add it correctly Commented Nov 21, 2013 at 10:25

3 Answers 3

3

Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.

If you want to assign a function, then you need to pass the function itself.

...onclick = myFunction;

If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.

...onclick = function () {
        myFunction("arguments");
    };
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it good explanation. so if i want to pass argument, and want to separate the script and the element to make it more readable, the best thing i can do is your second code in my js file?
2

Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...

//bind event listener
        function initialize(){
             document.getElementById("thediv").onclick = function () { myFunction(" something "); };    
        }
//end of bind

Comments

2

Instead of assign you invoke a function with myFunction(); Use it like this

//bind event listener
 function initialize(){
    document.getElementById("thediv").onclick = function(){
         myFunction(" something ");
   }
 }

Comments

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.