Capturing events in javascript - javascript

<!doctype html>
<html>
<body>
<div id = 'div' style = 'width:100px;height:100px;background:#000000;'></div>
<script type = 'text/javascript'>
document.getElementById('div').addEventListener('click',happen(),true);
function happen()
{
alert(1)
}
</script>
</body>
</html>
In the above code why the event is triggered when the page loads and not triggered when i click on the div...Also which is the correct event name click or onclick....

It's because you've immediately called the function, and passed its null result to addEventListener().
It should be:
document.getElementById('div').addEventListener('click',happen,true);
If you want to pass arguments to happen, you'd have to write this:
document.getElementById('div').addEventListener('click', function() {
happen(args_here, ...);
}, true);

You're calling the function immediately and passing its return value to addEventListener, just like any other function call.
Take out the ().

This should work:
document.getElementById('div').addEventListener('click',happen,true);

The problem is with this line:
document.getElementById('div').addEventListener('click',happen(),true);
You should should only be passing the name of the function happen but since you added the parentheses, you are passing the result.
Try this instead:
document.getElementById('div').addEventListener('click',happen,true);

As the other answerers have said, taking out the () will fix the problem.
An alternative, and a good practice for OO Javascript, is to wrap the function inside a function(){ }, like so:
document.getElementById('div').addEventListener('click',function(){happen()},true);
That will retain scope if the callback needs to execute within an object (in this case it does not).

The event handler does not need parenthesis
document.getElementById('div1').addEventListener('click',happen,true);

Related

Better understanding JavaScript parameters

I don't understand some parts of JavaScript code regarding parameters. I found this example on W3schools:
<!DOCTYPE html>
<html>
<body>
<a id="myAnchor" href="http://w3schools.com/">Go to W3Schools.com</a>
<p>The preventDefault() method will prevent the link above from following the URL.</p>
<script>
document.getElementById("myAnchor").addEventListener("click", function(event){
event.preventDefault()
});
</script>
</body>
</html>
I am confused with event parameter inside function. This code works although event parameter didn't become an argument, that is, it doesn't have any value. How can this "empty" parameter be used with a method. Why this code works? I am new to JavaScript so any simple answer would be appreciate.
Slit,
The function which is being called on "click" event is a "call-back" function. Once the event "click" raises then the anonymous "call-back" function which is "function(event){" is being called immediately with 1 parameter which is "event". In order to determine the parameters which will the anonymous function called with you should refer to documentation.
After you find the parameters, you may use and work with them inside this function, for example add "event.preventDefault(); alert('test')" and nothing will happen when you click on element, only popup window with "test" will arise.
Don't hesitate to ask any questions so I can improve my answer.. Just tried to explain in high level.
This function is also known as a callback. A callback is when you pass one function as an argument to another.
Try testing this code and then click anywhere on the page:
window.addEventListener("click", click);
function click() {
console.log(arguments);
}
If you open the console you should see [MouseEvent]. The special arguments object returns all the arguments received by the function. The click function received only one argument MouseEvent because the window method addEventListener sends an event to the event handler.
Here's a similar example:
init("abc", logArgs); //--> "abc"
init("abc", logDog); //--> "dog"
function logArgs(x) {
console.log(x);
}
function logDog(x) {
console.log("dog");
}
function init(x, callback) {
callback(x);
}
The confusing part about your example is that you can send a function an anonymous function. An anonymous function is one that is not named. Using the above example, you could do this:
init("abc", function(y) { //the y parameter comes from the init function
console.log(y); //"abc"
});
function init(x, callback) {
callback(x); //send the first argument to the anonymous function
}

Call a javascript handler with parameters

I have a method that calls another method (on ajax load, but that's irrelevant for this question). I'd like to pass parameters to this method. How is this possible?
The below page should scroll to id 25 on button click (the scrollable area is dynamically added in codebehind. this is just an example of what I'm attempting to accomplish)
JS
<%# Page Language="C#" Inherits="APTEIT.scrolltest" %>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function callHandler(handler) {
handler();
}
function scroll(id) {
alert("scrolling");
$("#divy").scrollTop($("#"+id).position().top);
}
</script>
<input type="button" value="scroll" onclick='var scroll={param1: "25"};callHandler(scroll)' />
</body>
</html>
You don't seem to pass the parameter into the handler in the callHandler method - instead, you try to invoke the scroll parameter (which is var scroll={param1: "25"}) as a function.
You use the same name scroll both for a config object and a function name. Please use different names :) Moreover, your declared and used function signatures do not agree. The scroll function accepts a string id while you are trying to pass in an object instead.
Unless I misunderstood, if handler is a function then pass arguments to it like any normal scenario.
function callHandler(handler){
var passme = "test";
handler(passme);
}
Update 1
I think what you might be able to do in this instance is the use the this keyword in the context of the input element. What this will ultimately do in your instance is replace id with this. This will also remove the additional select. Try this:
function callHandler(handler)
{
handler();
}
function scroll()
{
$("#divy").scrollTop($(this).position().top);
}
this might not work, as I'm not sure if the context will be that of input, or callHandler, give it a go! :)
Original
You should just be able to pass the parameters into the handler like so:
function callHandler(handler)
{
var param = 'Hello world';
handler(param);
}
callHandler(function(phrase)
{
alert(phrase);
});
put the parameters into an object like so:
var handler = {
param1: 'val1',
param2: 'val2' //ect...
}
handler(handler);
EDIT:
changing:
$("#divy").scrollTop($("#"+id).position().top);
to:
$("#divy").scrollTop($("#"+id.param1).position().top);
should work for your edited question.

Why isn't this setInterval working?

The code:
setInterval("doSomething()", 2000);
function doSomething(){alert('hi')}
demo: http://jsfiddle.net/PRff7/
I've been reading about this and I just can't get the example to work :(
Your code isn't executing because of jsfiddle. It wrapped your code in an onload handler, thus keeping doSomething out of the global namespace. So when setTimeout tried to execute your code, it couldn't find doSomething. Change jsfiddle to execute "no wrap", and all is well: http://jsfiddle.net/gilly3/PRff7/3/
If you don't wrap your call to doSomething in a string, it will also work because setInterval gets a direct reference to doSomething which is in the same scope. It doesn't need a global reference.
You need to change it to
setInterval(doSomething, 2000);
function doSomething(){alert('hi')}
You shouldn't pass a string to setInterval.
Instead, pass the function itself:
setInterval(doSomething, 1000);
If you want to leave your code inline, and not to delegate it to some named function (especially if code consists of more than one command), use this:
setInterval( function(){ alert('hi'); alert('hello') }, 2000);

why the function call does not work this way?

This is the script that i tested when the page loads.
window.onload = initAll;
function initAll() {
document.getElementById("pTag").innerHTML = "Hello Java Script !";
}
The above script works fine till i put parenthesis like initAll() during the call. _( window.onload=initAll(); )_ . Nothing happens if use initAll() during function call. It is like the script wasn't there.
Why is it so ?
window.onload expects the value you set for it to be a function (functions are like any other object in JavaScript).
If you put parens after initAll, you actually invoke the function and set window.onload to the function's return value. Since the function does not return anything explicitly, this value is undefined. So in practice you can think of this code:
window.onload = initAll();
function initAll() {
// do something with document
}
as equivalent to this code:
var result = initAll();
window.onload = result;
function initAll() {
return null;
}
I 'm sure you can immediately see why this would not work.
Because you should not execute the function at that line, you should assign an event handler to the window object, which will be triggered/executed once the load event has fired, not the returned value of a function.
However, assigning an event handler window.onload is not recommended, because it will allow for only one handler to be attached. Consider using addEventListener.
Because you're not calling the function directly in the window.onload statement, but you're assigning a function to the onload event. The system will then automatically call your initall function when the event happens. Thats why you need the function itself (without parenthesis), and not the call (with parenthesis)
This has to do with the way Javascript works. Functions also are actually objects, like about everything in javascript.
So basically, you are assigning the "Object" initAll , which happens to be a function, to window.onload . This object is then called when the onload event is triggered, assuming it is a function.
Now, when you are putting parenthesis behind your objects name, you are basically telling it to treat that object like a function and call it. this is not the way how to assign it to a property, like the window.onload property.
window.onload = initAll;
You're binding the initAll function to the onload event of the window object. The function becomes the load handler. Now, when the load event fires at the window object, this function will be invoked.
window.onload = initAll();
You're immediately invoking the function initAll. this invocation returns undefined (in your case), and that undefined value will be assigned to window.onload. Assigning the undefined value to onevent properties obviously has no effect.
When you omit the parentheses in this call:
window.onload = initAll;
You are assigning to the window.onload event the reference value of the function initAll(). This causes the function to execute when the onload event is called because they share the same reference point. When you use the assignment like this:
window.onload = initAll();
You are assigning to the window.onload event the returned value of the function, which in this case is null.

jQuery's .click - pass parameters to user function

I am trying to call a function with parameters using jQuery's .click, but I can't get it to work.
This is how I want it to work:
$('.leadtoscore').click(add_event('shot'));
which calls
function add_event(event) {
blah blah blah }
It works if I don't use parameters, like this:
$('.leadtoscore').click(add_event);
function add_event() {
blah blah blah }
But I need to be able to pass a parameter through to my add_event function.
How can I do this specific thing?
I know I can use .click(function() { blah }, but I call the add_event function from multiple places and want to do it this way.
For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.
Here's some code to illustrate what I mean:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
You need to use an anonymous function like this:
$('.leadtoscore').click(function() {
add_event('shot')
});
You can call it like you have in the example, just a function name without parameters, like this:
$('.leadtoscore').click(add_event);
But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:
$('.leadtoscore').bind('click', { param: 'shot' }, add_event);
And access it in add_event, like this:
function add_event(event) {
//event.data.param == "shot", use as needed
}
If you call it the way you had it...
$('.leadtoscore').click(add_event('shot'));
...you would need to have add_event() return a function, like...
function add_event(param) {
return function() {
// your code that does something with param
alert( param );
};
}
The function is returned and used as the argument for .click().
I had success using .on() like so:
$('.leadtoscore').on('click', {event_type: 'shot'}, add_event);
Then inside the add_event function you get access to 'shot' like this:
event.data.event_type
See the .on() documentation for more info, where they provide the following example:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.
//click handler
function add_event(event, paramA, paramB)
{
//do something with your parameters
alert(paramA ? 'paramA:' + paramA : '' + paramB ? ' paramB:' + paramB : '');
}
//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});
//or use variables
var a = 'first',
b = 'second';
$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});
$imgReload.data('self', $self);
$imgReload.click(function (e) {
var $p = $(this).data('self');
$p._reloadTable();
});
Set javaScript object to onclick element:
$imgReload.data('self', $self);
get Object from "this" element:
var $p = $(this).data('self');
I get the simple solution:
<button id="btn1" onclick="sendData(20)">ClickMe</button>
<script>
var id; // global variable
function sendData(valueId){
id = valueId;
}
$("#btn1").click(function(){
alert(id);
});
</script>
My mean is that pass the value onclick event to the javascript function sendData(), initialize to the variable and take it by the jquery event handler method.
This is possible since at first sendData(valueid) gets called and initialize the value. Then after jquery event get's executed and use that value.
This is the straight forward solution and For Detail solution go Here.
Since nobody pointed it out (surprisingly). Your problem is, that $('.leadtoscore').click(add_event); is not the same as $('.leadtoscore').click(add_event('shot'));. The first one passes a function, the second a function invocation so the result of that function is passed to .click() instead. That's not what you want. Here's what you want in vanilla JavaScript terms:
$('.leadtoscore').click(add_event.bind(this, 'shot'));
Function.prototype.bind() passes the function to .click() just like in the first example but with bound this and arguments that will be accessible on invocation.

Categories

Resources