JavaScript notifications onclick event - javascript

as soon as Notification instantiates onclick function fires but I want prevent this event before actual click occures on notification
var message = new Notification("RandomString");
message.onclick(alert("Random Message"))

Try this:
var message = new Notification("RandomString");
message.onclick = function(){alert("Random Message")};

I'm going to break this down a little bit to make it more clear what your code is doing.
message.onclick() will invoke the onclick property of message, which is probably currently null and therefore can't be called as a function.
Inside of the () you have alert("Random Message"), which is going to be called right then. This means that the value of that function call will be passed in to the onclick function call as a parameter. alert() doesn't return anything, so the alert fires, then you're left with this:
message.onclick('undefined')
What you wanted to do was make onclick a function and have it call the alert.
message.onclick = function() {
alert("Random Message")
};
Now you can fire that function by clicking the element it is attached to, or you can still fire it directly with message.onclick().
The best practice now is to use addEventListener rather than onclick. addEventListener will allow you to register multiple events of the same type.
message.addEventListener('click', function() {
alert("Random Message");
});
Another thing that newer programmers often don't realize is that you don't have to make the function while attaching it as the event listener. Here's an example using both methods:
function foo() {
alert("Random Message");
}
message.onclick = foo;
message.addEventListener('click', foo);

Related

how could the callback function of addEventListener() works even if we didn't pass the event object into the function

const eventHandler = function (eventObject) {
console.log('You clicked on the page')
console.log(eventObject)
}
document.addEventListener('click', eventHandler)
So the codes above, as you can see we are listening to the click event on the page, with a "seperated" callback function, or an event handler function named eventHandler. And you can see this eventHandler function it expects an eventObject parameter which is the event object itself.
You can see, when i pass the function eventHandler into the addEventListener() method, i didn't passing any argument, right? So i didn't pass the eventObject into it. But, when i run the codes, the codes still running without error, so when i clicked on the page, i get a You clicked on the page message, and the event object.
Why is that? How could that function can log the event object into the console, when it requires us to pass the event object into it as an argument and we didn't do that? And that is my question. I got into this situation when playing around with DOM event, and it really make me confused. So hopefully someone can help me understand, what's going on here! Thank you very much!
Sorry you may want to run this codes on yourself, I will update the demo later, thank you so much!
The reason you don't need to pass an event as a parameter to the function eventHandler that you are calling in the document onclick event listener, is because it already has an event that has been registered to it in the function
const eventHandler = function (eventObject) {
console.log('You clicked on the page')
console.log(eventObject)
}
// document.addEventListener('click', eventHandler)
// This function above is the exact same as the one here below
// That's why it works, because the event object has already been passed to the function
document.addEventListener('click', function(eventObject){
console.log('You clicked on the page')
console.log(eventObject)
})
<h2>Click anywhere to run the function</h2>

Does window.onload pause the script or simply awaits till value is true and runs the statement?

Out of curiosity if I am using for example.
window.onload = function() {
testFunction();
};
function testFunction() {
alert("Hello World!");
}
Does this pause the script or simply waits till the window load value is true and run the statement? I am sure its the latter but to better understand script behavior I was curious to find answer with more knowledgeable coders.
window.onload = ... is just an assignment: it stores a function in the window.onload variable. When an event happens, the JavaScript engine looks at the corresponding onsomething property and runs the function assigned to that variable. In fact, this would be valid as well:
function testFunction() {
alert("Hello World!");
}
window.onload = testFunction;
The same thing is true for functions bound with the addEventListener function.
window.addEventListener("load", function(e) {
// do something
});
window.addEventListener("load", function(e) {
// do something else
});
This simply adds functions to an underlying list of functions which will be called when the load event happens. This is required when you need to bind multiple events to the same object.
It's an event listener.
See documentation here: http://www.w3schools.com/js/js_htmldom_events.asp
and here:http://www.w3schools.com/js/js_htmldom_eventlistener.asp
You might like to try the Visual Event extension for Chrome. It shows you all event listeners that are currently attached to the page displayed.

JavaScript calling a function without parenthesis

A few weeks ago I was painfully able to dynamically add buttons to an HTML DOM object that has its own .on('click'.. handler, and use e.stopPropgation to stop these new child elements from firing the event.
The weird thing I did was call a function without any parenthesis. I have no idea why I did this or why it works, or why it does not work when I do attach parenthesis. I want to know if I am doing something by fluke and not design (and now I will add comments to it).
It goes as such:
//Container is the parent element
// var buttons stores the buttons with class 'buttons'
$('.container').on('click', function(){
$(buttons).appendTo($(this)).fadeIn(500).find('.buttons').click(tableButton);
});
function tableButton(e){
e.stopPropagation();
//do stuff
}
I can't figure out why I wrote the call to tableButton with no arguements or why it works perfectly. I tried to change the syntax to
.find('.buttons').on('click', function(e){
tableButton(e);
});
but then it no longer works.
Any help appreciated!
It works because you're passing a function to the click handler rather than calling the function yourself (the ()) An example of that:
var testFunction = function(msg) {
alert(msg);
}
var functionCaller = function(functionToCall) {
functionToCall('hello!');
}
functionCaller(testFunction);
functionCaller passes the message argument to testFunction(), but we only pass testFunction to functionCaller (without arguments)
For the part which doesn't work, isn't the function name tableButton() instead of tableButtons()?
See http://jsfiddle.net/g2PAn/
You don't actually call it, you just declare it and the arguments it accepts. The click callback is called with an argument indeed, but not by you.
The problem probably comes from the fact that jQuery calls your function with the element clicked bound as this, you could call table button like this:
.find('.buttons').on('click', function(e){
tableButton.call(this, e);
});

How to remove a callback function from jQuery widget

I have a widget that I am assigning a callback function to for a specific event.
The following code works and triggers my callback just fine.
$(selector).MyFancyWidget('option', 'onComplete', this._onComplete);
My issue is after the event fires I want to remove the callback from inside the _onComplete method.
onComplete is an event that gets fired in the widget using the _trigger method and works fine.
Doing something like
$(selector).MyFancyWidget('option', 'onComplete', $.noop);
Does not detach the callback ( i assume it is just adding another listener.
For clarity here is the code inside the widget that will trigger the event.
instance._trigger('onComplete', e, {currentTarget: instance});
So my question here is how do I remove that callback?
It's not that I don't want to fire the event anymore I just don't want to listen to it anymore.
The most straightforward way of doing this would be to make the callback only do something once. So wherever you define your _oncomplete function:
var completeRan = false;
this._onComplete = function(e, args) {
if (completeRan) {
return;
}
// Rest of your code.
completeRan = true;
return this;
}

inline javascript onclick event

This is my html code
Hit
This is my javascript file
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
But when i click the Hit Link, it redirects.
you need to pass in the event if you wish to preventDefault.
html:
Hit
script:
function runFunction (evt) {
evt.preventDefault();
evt.stopPropagation();
}
To tie both of the very-correct answers together, what's happened is you've inlined a function where you've written onclick="return runFunction();"
If you look at that, what it's really doing is going like this:
var link = document.getElementById("myLink");
link.onclick = function () { runFunction(); };
See the problem?
My runFunction is being called without any event object passed in, at all.
...which means that var thisLink = (evt) ? is going to return false, which means that it's going to try to run in oldIE-mode.
By writing onclick="runFunction", that's the same as saying:
link.onclick = runFunction;
Which means that when the onclick event happens, runFunction will be called, and in W3C-compliant browsers, it will be sent an event object.
Which is why that solution works.
The best way to avoid a lot of this confusion is to deal with JavaScript from inside of JavaScript, and to deal with HTML inside of HTML, so that you don't have to worry about how strings translate into code.
Now, to get all of this to work, AND prevent redirection, you want to do this:
for W3C browsers (the ones that pass the event parameter):
function runFunction (evt) {
// stops the default-action from happening
// means you need to find another way to fire it, if you want to later
evt.preventDefault();
// stops higher-up elements from hearing about the event
// like if you stop a submit button from "clicking", that doesn't stop the form
// from submitting
evt.stopPropagation();
//the oldIE versions of both of these are
event.cancelBubble = true;
event.returnValue = false;
}
When I plugged your code into chrome, I got this as the error in the console:
Uncaught TypeError: Cannot read property 'srcElement' of undefined
IF the javascript bombs out while processing, it never gets a chance to return at all so the browser tends to disregard what is in the onclick handler after the exception.
Since it bombed out... default behavior of anchor tags, which is to send you off to wherever the href says to go.
Try wrapping the contents of the function in a try/catch block and see what turns up if this kind of thing plagues you.

Categories

Resources