Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
sonal

Event Handling And Functions

Recommended Posts

I understand that ch. 6,7, 8 are most important basics to understand. I'm getting confused as I read over them.

 

1. event listener and event handler are used form same thing? Please correct me if I am wrong. I get it that a function written to do something for an event is referred as either event listener or event handler.

 

2. Can I assign a function with argument for event handling? Like, I have to create a JavaScript game of 2 players. I want to disable/enable player's button to give each one a turn. I'm doubtful about the logic, but copying the code to show what I want to ask. How to handle such functions? or what am I missing?

 

 

function dice() {

'use strict';

var diceno = Math.floor(Math.random()*6 + 1);

document.getElementById("dice").innerHTML = diceno;

}

 

 

function toggleButton(bt) {

'use strict';

dice();

b.disabled = true;

if(b.value == 'b2') { //here b.value does not give the name or id of button, as button is a input, and it's value property isundefined.

console.log(b.value);

document.dcForm1.b1.disabled = false;

} else {

console.log("b1");

document.dcForm1.b2.disabled = false;

 

}

}

 

window.onload = function() {

'use strict';

document.getElementById('b1').onclick = toggleButton; //This thing does not work, as it requires a parameter.

document.getElementById('b2').onclick = toggleButton;

}

Share this post


Link to post
Share on other sites

1) Yes, an event listener and an event handler are essentially the same thing.

 

2) Yes, you can send arguments to functions by using anonymous functions. For example:

 

elem.onmouseover = function () {

 someFunction(arg);

};

 

That answer your questions?

  • Upvote 1

Share this post


Link to post
Share on other sites

 

2) Yes, you can send arguments to functions by using anonymous functions. For example:

 

elem.onmouseover = function () {

 someFunction(arg);

};

 

Ok, got it. Create an another (anonymous) function assigning an event which can take a function with argument.

Thanks

  • Upvote 1

Share this post


Link to post
Share on other sites

Exactly. Keep in mind that using an anonymous function will not preserve the context of "this" in the function being called though, so you have to explicitly pass "this" as an argument, if you want to use it in the function being called.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×