Passing event data in the inline event handlers - javascript

I have an <input> which has an onkeydown inline event handler. In this handler, I'd like to call a function and pass a special parameter to it - the event data.
When I want to handle events (e.g. onmousemove) for the whole document, I use the following code:
document.onmousemove=function(e) {
// here I can make a good use of the 'e' variable,
// for example extract the mouse coordinates from it
}
And it works (although I don't know where the e variable - event data - comes from).
But this time I want to use the function only for the <input> mentioned above.
I need to pass the event data to the function so it can get the pressed key's code. And I want to do it in that inline event handler. I've created a function:
function myfunc (e) {
var evt=window.event?event:e;
var code=evt.keyCode;
alert (code);
}
and tried all of these methods:
<input onkeydown="myfunc(this)">
<input onkeydown="myfunc(this.onkeydown)">
<input onkeydown="myfunc(onkeydown)">
But none of them worked, the alert window kept displaying "undefined".
I looked for a solution to my problem in Google, but didn't find anything that could help me solve it.

<input onkeydown="myfunc(event)">
function myfunc (e) {
e = e || window.event;
var code = e.keyCode;
alert (code);
}

Related

What is the returned value of a clicked <button>?

I want to get the returned value of a clicked button, and then use it to make an if statement. All the answers that I read here about people trying to do that are either very old using old script that doesn't work anymore, or not the same case.
function remove() {
if (document.getElementById("removing").value == true) {
document.getElementById("test").style.backgroundColor = "red";
}
}
<div id="test">test</div>
<button id="removing" onclick="remove()">Remove a word</button>
I have tried using the value property, and onclick, but non of them equal true when the button is clicked.
I tried using alert to display the value, but it displays nothing.
Does clicking a button actually returns a value, and if so, what is it?
DOM Events are handled by an EventListener's callback function.
Thus such a handler function, if triggered by an event and forwarded by an event listener's handleEvent method, always will be invoked with an event object as this function's single argument.
All information related to this event are carried by the event itself. Its properties can be read and some even can be written/changed.
It is obvious from the provided example that the OP wants to assure that an event handler has been triggered by just a specific html element. Thus any valid approach just needs to look into the event's currentTarget property ...
// the way the OP might want to handle the problem.
function handleRemoveWord(evt) {
const elmNode = evt.currentTarget;
// make sure the handler was
// triggered by the intended element ...
// ... here by comparing node properties.
if (
(elmNode.tagName.toUpperCase() === 'BUTTON')
&& (elmNode.id === 'remove')
) {
document
.getElementById('test')
.style.backgroundColor = 'red';
}
}
// another way the OP might want to handle the problem.
function handleRemoveAnotherWord(evt) {
// `this` referres to the element which got
// bound to the handler via `addEventListener`.
const targetNode = this;
// make sure the handler was
// triggered by the intended element ...
// ... here by comparing node references.
if (targetNode === evt.currentTarget) {
document
.getElementById('test')
.style.backgroundColor = 'cyan';
}
}
// an alternative way of solving the problem
// of always being assured about the correct
// element having triggering the event handling.
function handleRestoreWordWithBoundContext(evt) {
const context = this;
const { elmTest, elmRestore } = context;
// make sure the handler was
// triggered by the intended element ...
// ... here by comparing node references.
if (elmRestore === evt.currentTarget) {
elmTest.style.backgroundColor = '';
}
}
function initialize() {
// the way(s) the OP might want to handle the problem.
document
.getElementById('remove')
.addEventListener('click', handleRemoveWord);
document
.querySelector('#removeAnother')
.addEventListener('click', handleRemoveAnotherWord);
// an alternative way of soving the problem
// of always being assured about the correct
// element having triggering the event handling.
const elmTest = document.querySelector('#test');
const elmRestore = document.querySelector('#restore');
elmRestore.addEventListener(
'click',
handleRestoreWordWithBoundContext.bind({
elmTest,
elmRestore,
})
);
}
initialize();
<div id="test">test</div>
<button id="remove">Remove a word</button>
<button id="removeAnother">Remove another word</button>
<button id="restore">Restore a word</button>
As one might have noticed, the example features a third button with yet another way of implementing an event handler. This additional handler assumes its this context to carry additional information. This is possible by invoking bind on this handler function and providing exactly the information one wants to be present as the event handlers this context. Every time this function specific method is invoked it creates another function which does have access to the bound information via the this keyword.
Simply change background color onClick of button as:
function remove() {
document.getElementById("test").style.backgroundColor = "red";
}
<div id="test">test</div>
<button id="removing" onclick="remove()">Remove a word</button>
Dispatching Javascript event handlers always returns true, even if it returns false, which we all know is used to prevent default behaviour of an event. We don't usually use the return values of Event handlers or even return anything for that matter.
In your case, I think you're trying to acess the value of the currentTarget element(the button 'removing' in your case). For this you can use the event object, which gets passed on as parameter to your event handler.
event.currentTarget is a way of referencing the element on which an event is being dispatched(triggered) on. It's just like using 'this' inside the event handler, except it also works on arrow functions.
So do something like this:
function remove(event) {
let button = event.currentTarget;
if (buttton.value) {
document.getElementById("test").style.backgroundColor ="red";
}
}
and in HTML,
<div id="test">test</div>
<button id="removing" onclick="remove(event)">Remove a word</button>
Notice I've used remove(event).
Edit Based on comment below:
Using onclick will require you to create you a global 'remove' function.
If you do, '...onclick="remove(event)" what it basically does is creates the function below, a wrapper basically:
// In the global scope
[reference element].onclick = () => {
remove(event);
}
So you must have a global 'remove' function. So this won't work in modules cause each modules have their own top level scope. And you're gonna wanna have to use modules if you plan to work on sophisticated projects.
NOTE Using inline 'onclick' attributes in html has following disadvantages on heavy requests from a comment below:
-separation of concern : You usually don't want to mix up your UI logic(what happens on clicking a button) with presentation. You want a clear split between content, style and script.
-only one handler can be assigned using onclick.
-if an event is specified inline, the JS is specified as a string (attribute values are always strings) and evaluated when the event fires.(extra wrapper code builds internally).
-as I've mentioned before, you are faced with having to reference named functions. This is not ideal and has implications on the function needing to be global which will really bite you back when you use modules.
In short, handle events centrally via the dedicated addEventListener API.

Call change event of an input programatically [duplicate]

How do I programmatically force an onchange event on an input?
I've tried something like this:
var code = ele.getAttribute('onchange');
eval(code);
But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.
Create an Event object and pass it to the dispatchEvent method of the element:
var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);
This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.
By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.
If you want the event to bubble, you need to pass a second argument to the Event constructor:
var event = new Event('change', { bubbles: true });
Information about browser compability:
dispatchEvent()
Event()
In jQuery I mostly use:
$("#element").trigger("change");
ugh don't use eval for anything. Well, there are certain things, but they're extremely rare.
Rather, you would do this:
document.getElementById("test").onchange()
Look here for more options:
http://jehiah.cz/archive/firing-javascript-events-properly
For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
I did however, create a test page that confirmed calling should onchange() work:
<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>
Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.
Taken from the bottom of QUnit
function triggerEvent( elem, type, event ) {
if ( $.browser.mozilla || $.browser.opera ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( $.browser.msie ) {
elem.fireEvent("on"+type);
}
}
You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.
To use this function:
var event;
triggerEvent(ele, "change", event);
This will basically fire the real DOM event as if something had actually changed.
This is the most correct answer for IE and Chrome::
var element = document.getElementById('xxxx');
var evt = document.createEvent('HTMLEvents');
evt.initEvent('change', false, true);
element.dispatchEvent(evt);
If you add all your events with this snippet of code:
//put this somewhere in your JavaScript:
HTMLElement.prototype.addEvent = function(event, callback){
if(!this.events)this.events = {};
if(!this.events[event]){
this.events[event] = [];
var element = this;
this['on'+event] = function(e){
var events = element.events[event];
for(var i=0;i<events.length;i++){
events[i](e||event);
}
}
}
this.events[event].push(callback);
}
//use like this:
element.addEvent('change', function(e){...});
then you can just use element.on<EVENTNAME>() where <EVENTNAME> is the name of your event, and that will call all events with <EVENTNAME>
The change event in an input element is triggered directly only by the user. To trigger the change event programmatically we need to dispatch the change event.
The question is Where and How?
"Where" we want the change event to be triggered exactly at the moment after a bunch of codes is executed, and "How" is in the form of the following syntax:
const myInput = document.getElementById("myInputId");
function myFunc() {
//some codes
myInput.dispatchEvent(new Event("change"));
}
In this way, we created the change event programmatically by using the Event constructor and dispatched it by the dispatchEvent() method. So whenever myFunc() method is invoked, after the //some codes are executed, our synthetic change event is immediately triggered on the desired input element.‍
Important result: Here, the change event is triggered by executing the //some codes in myFunc() instead of changing the input value by the user (default mode).
if you're using jQuery you would have:
$('#elementId').change(function() { alert('Do Stuff'); });
or MS AJAX:
$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });
Or in the raw HTML of the element:
<input type="text" onchange="alert('Do Stuff');" id="myElement" />
After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:
$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
alert('Do Stuff!');
}
function editElement(){
var el = $get('elementId');
el.value = 'something new';
elementChanged();
}
Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.
Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:
$get('elementId')._events
It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.
Using JQuery you can do the following:
// for the element which uses ID
$("#id").trigger("change");
// for the element which uses class name
$(".class_name").trigger("change");
For triggering any event in Javascript.
document.getElementById("yourid").addEventListener("change", function({
//your code here
})

Listen to a mouse event on condition

I want to "listen to" a mouse event only if a checkbox is clicked. Therefore I have the following code:
HTML
<input type="checkbox" id="magicLens" onchange="magicLens()">
<label for="magicLens">Magic Lens</label>
JS
function magicLens(){
const magicLens_checked = document.getElementById('magicLens').checked;
if (magicLens_checked === true){
canvas.addEventListener('mousemove', e => {
myAnonymous = arguments.callee;
...
// draw something at the current mouse position
// and therefore use the 'e' event object
});
}
else {
canvas.removeEventListener('mousemove', myAnonymous);
}
}
Problem is, that the drawing (a lens) also occurs when the checkbox is not checked (false). I'm not even sure if removeEventListener() is the right way to deal with it (though I already tried the whole thing without it and result was the same).
Maybe you have a better idea to describe the issue in the title. Feel free to edit!
It's easier to actually always listen to the event and in there check whether the checkbox is checked.
const canvas = document.getElementById('canvas');
canvas.addEventListener('mousemove', e => {
const magicLens_checked = document.getElementById('magicLens').checked;
if (!magicLens_checked) {
return;
}
// Do something with e
console.log(e);
});
You can check it out in this Fiddle. (I added the event listener to document, to avoid creating an arbitrary canvas, but it works the same way)
The Javascript engine sees what you pass to addEventListener and removeEventListener as two different functions which is why the removeEventListener is not working. Create a named function outside of these and pass it into them.

How to open up a tab in Javascript

I've got a page in which I create some tabs.
function addTab(ticketId, name) {
$('#pageTab').append(
$('<li>'+name+'<button class="close" type="button">×</button></li>'));
$('#pageTabContent').append($('\
<div class="tab-pane" id="'+ticketId+'">\
here some more html \
</div>'));
$('#page' + ticketId).tab('show');
}
When the user wants to open the contents of the tab I open the contents with this code:
$("#pageTab").on("click", "a", function (e) {
openTab(e, this);
});
which calls this function:
function openTab(e, tabId) {
e.preventDefault();
$(tabId).tab('show');
}
I now want to call this openTab function from a different place, but I actually no idea what this e variable does or where it comes from.
Does anybody know how I can call this function and supply that e variable? All tips are welcome!
e is the context of the event. Whenever an event occurs (click, scroll, keydown etc.) you get a context object that allows you to get more information about the event. This context object is generated for you.
If you call openTab programmatically then you don't have an event. Seeing as you only preventDefault() you don't need it anyway. Consider restructuring like this:
$("#pageTab").on("click", "a", function (event) {
event.preventDefault(); // we're handling a click, so we have an event, deal with it here
openTab(this);
});
function openTab(tabId) {
$(tabId).tab('show');
}
Now you can call:
openTab($("#some_tab"));
e looks like an event to me. You don't seem to be using it except with e.preventDefault() so you can either modify the functions to not parse it or modify the openTab() function to check if it's null then you can send it a null when calling the openTab() function.
so you could do this:
function openTab(e, tabId) {
if(e!=null){e.preventDefault();}
$(tabId).tab('show');
}
then call the function like this:
openTab(null,tabId);
Or modify openTab() to look like this:
function openTab(tabId) {
$(tabId).tab('show');
}
and modify all references to openTab() as to not send the e variable so they look like this:
openTab(tabId);

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

The following doesn't work... (at least not in Firefox: document.getElementById('linkid').click() is not a function)
<script type="text/javascript">
function doOnClick() {
document.getElementById('linkid').click();
//Should alert('/testlocation');
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
You need to apply the event handler in the context of that element:
var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
elem.onclick.apply(elem);
}
Otherwise this would reference the context the above code is executed in.
The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:
<script type="text/javascript">
function doOnClick() {
$('#linkid').click();
}
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
Tested in IE8-10, Chrome, Firefox.
To trigger an event you basically just call the event handler for that
element. Slight change from your code.
var a = document.getElementById("element");
var evnt = a["onclick"];
if (typeof(evnt) == "function") {
evnt.call(a);
}
Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.
document.getElementsByName('MyElementsName')[0].click();
In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).
document.getElementById('MyElementsId').click();
I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.
Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
$("#linkid").trigger("click");
Old thread, but the question is still relevant, so...
(1) The example in your question now DOES work in Firefox. However in addition to calling the event handler (which displays an alert), it ALSO clicks on the link, causing navigation (once the alert is dismissed).
(2) To JUST call the event handler (without triggering navigation) merely replace:
document.getElementById('linkid').click();
with
document.getElementById('linkid').onclick();
Have a look at the handleEvent method
https://developer.mozilla.org/en-US/docs/Web/API/EventListener
"Raw" Javascript:
function MyObj() {
this.abc = "ABC";
}
MyObj.prototype.handleEvent = function(e) {
console.log("caught event: "+e.type);
console.log(this.abc);
}
var myObj = new MyObj();
document.querySelector("#myElement").addEventListener('click', myObj);
Now click on your element (with id "myElement") and it should print the following in the console:
caught event: click
ABC
This allows you to have an object method as event handler, and have access to all the object properties in that method.
You can't just pass a method of an object to addEventListener directly (like that: element.addEventListener('click',myObj.myMethod);) and expect myMethod to act as if I was normally called on the object. I am guessing that any function passed to addEventListener is somehow copied instead of being referenced. For example, if you pass an event listener function reference to addEventListener (in the form of a variable) then unset this reference, the event listener is still executed when events are caught.
Another (less elegant) workaround to pass a method as event listener and stil this and still have access to object properties within the event listener would be something like that:
// see above for definition of MyObj
var myObj = new MyObj();
document.querySelector("#myElement").addEventListener('click', myObj.handleEvent.bind(myObj));
If you're using this purely to reference the function in the onclick attribute, this seems like a very bad idea. Inline events are a bad idea in general.
I would suggest the following:
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
handler = function(){
showHref(el);
}
showHref = function(el) {
alert(el.href);
}
var el = document.getElementById('linkid');
addEvent(el, 'click', handler);
If you want to call the same function from other javascript code, simulating a click to call the function is not the best way. Consider:
function doOnClick() {
showHref(document.getElementById('linkid'));
}
In general I would recommend against calling the event handlers 'manually'.
It's unclear what gets executed because of multiple registered
listeners
Danger to get into a recursive and infinite event-loop (click A
triggering Click B, triggering click A, etc.)
Redundant updates to the DOM
Hard to distinguish actual changes in the view caused by the user from changes made as initialisation code (which should be run only once).
Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.

Categories