Nesting two Javascript events - javascript

I'm trying to call a function through an eventlistener in Javascript, and within the function I have invoked another eventlistener. However on doing this, my second listener is completely ignored. Is there any condition which I need to follow to make this work?
document.getElementById("my_canvas").addEventListener("mouseenter", this.getAttention); //first event listener
getAttention: function(e){
document.addEventListener("onclick", function(){ console.log("Hello World!"); });
Here the "Hello World" is not consoled.
Please help.

It is ignored because the first parameter expects event string to be without "on", try this
document.addEventListener("click", function(){ console.log("Hello World!"); });

When invoking the addEventListener method you pass in the name of the event as the first argument. The name of the click event is 'click'.
document.addEventListener('click', myFunc);
The syntax for registering a click event handler as a HTML attribute is onclick
<button onclick="myFunc"></button>

Related

JavaScript preventDefault is not a fuction

I am trying to detect a click on a button using JavaScript and prevent the default action
<button onclick="myFunction(this)">Click Here</button>
function myFunction(event) {
event.preventDefault();
console.log("Function Has Run")
}
I am getting the error
event.preventDefault is not a function
Where am I going wrong?
Inside an onclick function, the value of this is the element, not the event.
event is the first argument to the onclick function.
You could do this:
onclick="myFunction(event)"
… but I'm honestly not sure if onclick attributes set up a local event variable of if this is the global event.
It is better to bind your event handlers with JavaScript instead:
document.querySelector('button').addEventListener('click', myFunction)
Then myFunction itself will be the event handler so the first argument passed to it will be the event object, and this will be the element to which the event handler is bound.
As long as you want to access the event inside, I have figured out that passing the event directly in your onclick attribute works the best.
If you wish to use a different this, you will have to bind it using bind, call or apply
Your code would look similar to this in the end:
<button onclick="myFunction.call('new this', event)">Click Here</button>
function myFunction(event) {
console.log(this); // "new this"
event.preventDefault();
console.log("Function Has Run")
}

jquery .off doesn't seem to work

so I'll be short: jquery .off() doesn't disable a listen I've set with .on.
html:
<span id="myspan">lol</span>
<button id="b1">jquery On</button>
<button id="b2">jquery Off</button>
js:
$("#b1").on("click", add);
$("#b2").on("click", del);
function add() {
$("#myspan").on("click", function(e) {
var a = 1;
testfunc(a, e);
});
}
function del() {
$("#myspan").off("click", testfunc);
}
function testfunc(num, event) {
alert(num);
}
So first we add to myspan the testfunc() by clicking the jquery On button. After we do that, if we click on the span, we get an alert. Next, we click the jquery off button. That is supposed to remove the listener but it doesn't. Even after that, when we click on myspan testfunc is still attached.
Why? And how can I remove it ?
Your parameters don't match
It doesn't because you bound to a different function (anonymous one). And then you're trying to unbind from testfunc... In order for your event (un)binding to work both parameters between on and off must match.
Possible workaround
If this is the only click event listener on the element, then it's be easiest way to unbind from your anonymous function by calling:
$("#myspan").off("click");
If you're binding several event handlers to click event on the same element then you can also distinguish them by providing namespaces and then use proper namespacing in off call.
$("#myspan").on("click.test", function(e) { ... });
...
$("#myspan").off("click.test");
Or use just namespace if you'd like to unbind several different event handlers that were bound using the same namespace:
$("#myspan").off(".test");
You're not binding the event handler to testfunc, you're binding it to an anonymous function, and whitin that function you're just calling testfunc, so you can't automatically unbind that.
It's either
$("#myspan").on("click", testfunc); // bind function
and then
$("#myspan").off("click", testfunc); // unbind function
or to unbind the anonymous function, just
$("#myspan").off("click"); // remove all handlers
or you can also namespace the handler
$("#myspan").on("click.test", function(e) {
var a = 1;
testfunc(a, e);
});
and to remove only that handler
$("#myspan").off("click.test");
In this simple case, replace your off call with this:
function del() {
$("#myspan").off("click");
}
You don't need to pass the handler function to the off call, and if you do, it will only remove that particular handler. However, you did not attach testfunc, but an anonymous function that just calls testfunc(). Therefore, your off call does nothing.
Also, you never assigned the variable testfunc.

how to bind again the click event for the button

I have a button on which i am attaching a click event. I have to unbind it after i click on it, and later on in my code i need to bind that click event on it again. I tried binding it again but that does not works. I can't use jquery 'live'. Is there any way to create a custom bind function on click event and then again call it ?
$(".submitButton").click(function(e){
//some functionality on click
$(".submitButton").unbind('click');
});
//somewhere ahead in my code
$(".submitButton").bind('click');
Apparently this isn't working. Is there any way to tackle this ?
Your .bind call doesn't seem correct. You haven't specified a callback.
So start by writing a function:
function handleButtonClick() {
//some functionality on click
$(this).unbind('click');
}
Notice that inside the handler I am unbinding $(this) which is the element being clicked and not all elements with class="submitButton".
and then:
$('.submitButton').bind('click', handleButtonClick);
and then later when you want to rebind:
$('.submitButton').bind('click', handleButtonClick);
and so on.
define your listener somewhere else:
function clickHandler() {
//some functionality on click
$(".submitButton").unbind('click', clickHandler);
}
$(".submitButton").bind('click', clickHandler);
//somewhere ahead in my code
$(".submitButton").bind('click', clickHandler);
When you use .bind() to bind an event handler it expects a function to be passed as well, since that's what will be executed when the event fires. Don't use an anonymous function, instead declare a named function and pass a reference to that when binding.
function handleClick(e){
//some functionality on click
$(".submitButton").unbind('click');
}
$(".submitButton").click(handleClick);
// somewhere else in your code (in reaction to some other event)
$(".submitButton").click(handleClick);
You can use jQuery.one(). Please refer below code.
$(".submitButton").one('click', clickHandler);
The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation.
you can call it or bind it whenever it necessary.

Why do you have to pass the event object as a parameter?

I'm learning how to manipulate events in JavaScript and I'm wondering "why do you have to pass the event object as a parameter (argument) into a function when using event handling?"
Here's an example of what I am talking about:
<script type="text/javascript">
document.getElementById('button_1').onclick = (function (event) {
alert("The event is: " + "on" + event.type);
});
</script>
I wrote the code above and I pretty much understand what it does. I just don't understand the whole (event) passing. I thought of this as a way of assigning an anonymous function to the button_1.onclick event handler. Does the event handler try to pass in an event before it gets assigned or?... I'm having a difficult time understanding this. If someone could please clarify this for me I would be grateful.
[I tried searching it on Google but found very complex explanations and examples. Only a simple-to-intermediate explanation would help.] =)
The Ever-Present Event, Whether You Like it or Not
The event is always present, even when you don't provide a name:
$(".foo").on("click", function(){
alert( arguments[0].type );
});
That is the same as saying this:
$(".foo").on("click", function(event){
alert( event.type );
});
The event object is already being passed to your callback (whether your provide a name for it or not), you can choose to not use it if you like. For instance, if we looked to a jQuery onClick method:
$(".foo").on("click", function(){
/* Do stuff */
});
Making Use of It
You'll note that I have no event object referenced in my callback. I'm not required to. However, if I want to use it, for whatever purpose, I should give it a name:
$(".foo").on("click", function(myEvent){
myEvent.preventDefault();
myEvent.stopPropagation();
});
Now that I have granted myself access to the event details, I can prevent the default behavior that would result from the event, and I can also stop the event from bubbling up the DOM to other elements.
Practical Example
Suppose we wanted to listen for click events on an element:
$("#bigSquare").on("click", function(event){
/* Do something */
});
Click events happen on an element when you click the element itself, or any of its children. Now suppose this element had two children:
<div id="bigSquare">
<div id="redSquare"></div>
<div id="blueSquare"></div>
</div>
Clicking any of these, the big square, the red square, or the blue square will cause the "click" event on the big square - after it causes the click event on whichever element you clicked first (events bubble up the DOM).
We could determine which element was the target in any click event via the event itself:
$("#bigSquare").on("click", function(event){
alert( event.target.id );
});
Note here how we're accessing the ID of the target that raised the event. If you click on the red square, when that event bubbles up to the big square, we will see alerted "redSquare". The same goes for the blue square. If you click that, the event will bubble up to the big square and we will see alerted "blueSquare".
You can test this online via the following demo: http://jsbin.com/ejekim/edit#javascript,live
Try clicking the orange, red, or blue square to see what is alerted.
You are not passing the event parameter anywhere. You are just making a function that takes one parameter, called event.
When the browser calls the event handlers, it calls the function(s) assigned to it, and passes the event object to it as the 1st parameter.
P.S. You don't need the () around your function.
document.getElementById('button_1').onclick = function (event) {
alert("The event is: " + "on" + event.type);
};
You aren't passing an event into the function, you are naming the first parameter passed to your function event.
The browser is the one that is going to call your function and it passes an event object when it calls your function. You can choose not to name that parameter function(){} but the browser is still going to pass the event object in, you can use it or not use it as you see fit.
Simply put, the Event object passed to a handler contains details about the event. For example, a KeyboardEvent contain info about the key pressed, the corresponding character, and any modifier keys (alt, shift, control, meta) that were held down.
Does the event handler try to pass in an event before it gets assigned or?
The handler is your function, so it's the receiver of event, not the passer.
The event handler is bound when you assign it to the element's onclick property (or by calling addEventListener, the modern, preferred method), which is before the handler is invoked.
The Event object is passed when the handler is invoked, which is when the event fires.
So, when a user clicks on your #button_1, this causes a "click" event to fire on the button, which invokes the button's "click" handler, which is passed a MouseEvent.
For more information, read about event-driven programming.
To add to the others answers and comments, your code will not work with IE. For cross-browser capability, you need to test the existence of the first argument:
<body>
<button id="button_1">Click Me!</button>
<script type="text/javascript" >
document.getElementById('button_1').onclick = (
function(event) {
var e = event ? event : window.event;
alert("The event is: " + "on" + e.type);
});
</script>
</body>

JavaScript: parameters for unnamed functions

In the following jQuery JavaScript code, what value does the parameter "e" take on within the function? I'm having difficulty understanding this because this function cannot be passed an argument elsewhere in the code so how would having a parameter work? And how would I use parameters in such functions that are not named and not called anywhere else in the code?
$(document).ready( function() {
$('div').each(function() {
$(this).click(function(e){
//some code
});
});
});
click sets the event handler. The click handler gets called by the browser when the event occurs, and the e parameter contains information about that event.
For keypress events, it contains which keys were pressed and what modifiers were pressed at that time (shift, control, etc.).
For mouse events, it contains the position of the click and which button was used.
See http://www.quirksmode.org/js/events_properties.html for more information about the properties of the event structure.
e is an eventObject as you can see in the jQuery click documentation.
I do not know what you can do with it however, but it should contain information about the click event. Maybe it's the standard DOM event.
That anonymous function is called when the event is fired, and e is an eventObject:
click( fn )
// fn, a function to bind to the click event on each of the matched elements.
function callback(eventObject) {
this; // dom element
}

Categories

Resources