JavaScript preventDefault is not a fuction - javascript

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")
}

Related

Add another event at runtime

I have this code:
and I would like to add at runtime by JS something like this:
My idea was doing like this but I dont know how to add AND operator:
form.addEventListener('submitForm', function (e) {
e.preventDefault();
alert('onclick handler called');
}, false);
To not change the HTML itself you can do this
window.addEventListener("load",function() {
let saveBut = document.querySelector('a[title="Save"]');
let form = document.querySelector("[name=thisForm]");
form.addEventListener("submit",function(e) { e.preventDefault(); }); // stop submission by other means than the link
saveBut.onclick=null; // remove the inline event handler
saveBut.addEventListener("click",function(e) {
e.preventDefault(); // stop the link's click
if (validate(e, form)) submitForm(form); // call submitForm if valid
});
});
'submitForm' is referenced as a function in your onclick attribute, but you're trying to use it as an event. It won't work like that, <form> doesn't emit an event called 'submitForm', and it's not being called when you call a submitForm function. <form> does have a submit event.
You should avoid using the onclick attribute (and other on* attributes). Use IDs and addEventHandler to add a click event handler. Then you can just write an entire multi-line function in that handler.
You can also use an <input> or <button> of type=submit and then add an event listener of type submit to the form (if your form is a <form> element). Then you will not need to call any other functions from event listeners. The form will handle that.

Returning Event Handler for an event in JavaScript

I want to know if is possible to get the event handler for any events in JavaScript that was set for an object using addEventListener or on("event",...) in jQuery.
The idea is to return a function object and then reassign that function object to another events, for example an event handler A was set for an event 'click' but remotely. then after loading the script remotely, i want to modify this event and set the event handler to point to focus instead of onclick. I have no either so i can't drop a code sample.
I am expecting a function object to reassign to another event type
Listeners attached with addEventListener cannot be fetched.
document.getElementById("clickMe").addEventListener("click", function(){alert("clicked");});
The best shot will be
document.getElementById("clickMe").click();
Listener attached using the HTML node onclick property like:
<button id="clickMe" onclick="alert('clicked');">Click Me</button>
can be fetched as
var handler=document.getElementById("clickMe").onclick;

Nesting two Javascript events

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>

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.

Categories

Resources