Unexpected Javascript onkeydown event and document.write - javascript

I am learning Javascript and when I am testing some features, I found some problems. Here are my codes:
<script>
function onCreate() {
var body = document.getElementsByTagName('body')[0];
body.focus();
body.onkeydown = function(e) {
if (e.keyCode == 32) {
alert(1);
sayHey();
}
}
}
function sayHey() {
document.write("Hey ");
document.write("May");
}, 30);
</script>
</head>
<body onload="onCreate()">
</body>
As you may try, onkeydown event works perfectly when I do not include sayHello() function, which make use of setInterval.
When sayHello() is included, when I click space bar, "Hey May" is created which is as expected. However, when I click space bar once more, no alert message and no new "Hey May" is raised. It seems that onkeydown() function do NOT work anymore. Why is it the case?
In addition, when I change document.write(brabrabra) to the below one, it works.
var newParagraph = document.createElement('p');
var text = "Hey May";
var textNode = document.createTextNode(text);
newParagraph.appendChild(textNode);
body.appendChild(newParagraph);
Why is it the case? Can someone explain to me please? Thanks a lot.

After the document has been parsed, the current document is closed and any use of document.write() will clear the current document and open a new blank document, thus clearing any event handlers or content you previously had.
So, in your specific example, the first key press triggers your event handler. That shows the alert(1) and then calls sayHey() which calls document.write() which clears the current document and thus your event handler is no longer there. So, for the second press of the space bar there is no event handler in place and nothing happens.
So, if you want to add content to the document after it has been loaded, then you should add the content with something like document.createElement() and .appendChild(), not document.write().

Related

Is it discouraged to use "onlclick" with HTML element while using "addEventListener" method?

Before I explain my question, this piece of code is going to be considered:
HTML:
<div>
<button type="button" id="btn" onclick="disAl()">Click</button>
</div>
JS:
function disAl(){
var x = document.getElementById("btn");
if(x.addEventListener){
x.addEventListener("click", altTxt);
}
else if (x.attachEvent){
x.attachEvent("onclick", altTxt);
}
}
function altTxt(){
alert("Hello");
}
Now, if I run the program and click the button first time, nothing happens. However, from the second click the alert pops up. Interestingly enough, when I remove onclick="disAl()" from button element, and also remove the function definition from the script, the problem gets fixed. Like the following:
var x = document.getElementById("btn");
if (x.addEventListener) {
x.addEventListener("click", altTxt);
}
else if (x.attachEvent) {
x.attachEvent("onclick", altTxt);
}
function ...
....
So does it mean onclick="disAl()" method is unnecessary in my case?
Here is what is happening:
First time: Because of this part onclick="disAl()", you are setting up button click handler to a function called disAl(). Due to this, you get inside the function disAl() when you click the button.
When inside, you are again setting up click event handler to altTxt. This causes two handlers to be chained to click event. Then when you click second time, let's see what happens.
Second time: Now when the click happens, first disAl() is called which again unnecessarily sets up altTxt as click event handler. Once this handler is over, altTxt is called and that is when you see the alert.
Second case when you remove the function:
In this case, you are setting up button click event handler when your page is loaded since it is not a function anymore. So when you click the button, you call altTxt and see the alert.
So, yes disAl() is unnecessary in your case. Also, as a good practice, event handlers should not be set in the html but they should be set in the code by addEventListener. This allows you to remove event listener if you so desire by calling removeEventListener().
Hope this helps!
Yes you are right you are selecting document by jquery and writing event listener on it so you can just use like following.
function altTxt(){
alert("Hello");
}
var x = document.getElementById("btn");
if (x.addEventListener)
{
x.addEventListener("click", altTxt);
}
else if (x.attachEvent)
{
x.attachEvent("onclick", altTxt);
}

The click event from javascript on a button doesn't fire

So, I was going through a tutorial on event handlers. I created a button as instructed and then when I click on it, I wanted an alert to be displayed. Thats it. But it wouldn't work. Here's my html code:
<button id="submit">Submit</button>
And here's my javascript code:
var myButton = document.getElementByID("submit");
myButton.onclick = function(){
alert("YOu clicked on this button");
}
I am using external js file and I've included it in the html from the head of the document.
document.getElementByID("submit"); -- it's Id instead of ID
Edit: I feel very bad for giving this one-liner as an answer, so to add to what others have said about learning how to use the browser's console as a debuggining tool, you should try to find an IDE/text editor with auto-completion to save you such headaches especially when you're just starting out.
You may have an issue where document.getElementById() is happening before the element is created on the page. Try including your JavaScript in an onload event, or include it after the button in your HTML.
As previously stated, use document.getElementById("submit") with lower case Id. Also, you may want to use setAttribute so the alert fires when the button is pressed instead of immediately opening a popup when the alert line is encountered.
<script language="javascript">
var myButton = document.getElementById("submit");
myButton.setAttribute("onclick", "alert('You clicked on this button')");
</script>
change from document.getElementByID to document.getElementById and make sure your script stay below all the elements in the body. Example:
<body>
<button id="submit">Submit</button>
<script type="text/javascript">
var myBtn = document.getElementById("submit");
myBtn.onclick = function()
{
alert("this is a click event button");
};
</script>
</body>
or you can put the script inside the <head></head> by add this event below to your script:
function initialize()
{
// paste your code in here
}
document.addEventListener("DOMContentLoaded",initialize,false);
Hope it work!
it maybe a typo. It is getElementById not ID

Virtual Keyboard with Jquery

I have a div that operates as a button. Once the button is clicked, I want it to simulate the pressing of a key. Elsewhere on Stackoverflow, people have suggested using jQuery.Event("keydown"); but the suggestions all use a .trigger() bound to the button as opposed to .click. So, my example code looks like this:
var press = jQuery.Event("keydown");
press.which = 69; // # The 'e' key code value
press.keyCode = 69;
$('#btn').click( function() {
$('#testInput').focus();
$(this).trigger(press);
console.info(press);
});
I've set up a dummy example at JSFiddle:
http://jsfiddle.net/ruzel/WsAbS/
Eventually, rather than have the keypress fill in a form element, I just want to register the event as a keypress to the document so that a MelonJS game can have it.
UPDATE: It looks like triggering a keypress with anything other than the keyboard is likely to be ignored by the browser for security reasons. For updating a text input, this very nice Jquery plugin will do the trick: http://bililite.com/blog/2011/01/23/improved-sendkeys/
As for anyone who comes here looking for the solution in the MelonJS case, it's best to use MelonJS's me.input object, like so:
$('#btn').mousedown(function() {
me.input.triggerKeyEvent(me.input.KEY.E, true);
});
$('#btn').mouseup(function() {
me.input.triggerKeyEvent(me.input.KEY.E, false);
});
I'm not sure why, but even though this is triggering the event correctly, it doesn't fill the input with the character.
I've modified the code to show that the document is indeed receiving keypress events when we say $(document).trigger(p)
Try it out:
http://jsfiddle.net/WsAbS/3/
var press = jQuery.Event("keydown");
press.which = 69; // # Some key code value
press.keyCode = 69;
press.target = $('#testInput');
$(document).on('keydown', function(event) {
alert(event.keyCode);
});
$('#btn').click( function() {
$(document).trigger(press);
});
I believe this should be good enough for your end goal of a MelonJS game picking up keypresses.
If you want a virtual keyboard (As the title suggests) you can use this one.

Why is my onchange function called twice when using .focus()?

TLDR
Check this example in chrome.
Type someting and press tab. see one new box appear
type something and press enter. see two new boxes appear, where one is expected.
Intro
I noticed that when using enter rather then tab to change fields, my onchange function on an input field was firing twice. This page was rather large, and still in development (read: numerous other bugs), so I've made a minimal example that shows this behaviour, and in this case it even does it on 'tab'. This is only a problem in Chrome as far as I can tell.
What it should do
I want to make a new input after something is entered into the input-field. This field should get focus.
Example:
javascript - needing jquery
function myOnChange(context,curNum){
alert('onchange start');
nextNum = curNum+1;
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum).focus();
return false;
}
HTML-part
<div>
<input type="text" onchange="return myOnChange(this,1);" id="prefix_1">
</div>
the complete code is on pastebin. you need to add your path to jquery in the script
A working example is here on jFiddle
The onchange gets called twice: The myOnChange function is called, makes the new input, calls the focus(), the myOnChange gets called again, makes a new input, the 'inner' myOnChange exits and then the 'outer' myOnchange exits.
I'm assuming this is because the focus change fires the onchange()?. I know there is some difference in behaviour between browsers in this.
I would like to stop the .focus() (which seems to be the problem) to NOT call the onchange(), so myOnChange() doesn't get called twice. Anybody know how?
There's a way easier and more reasonable solution. As you expect onchange fire when the input value changes, you can simply explicitly check, if it was actually changed.
function onChangeHandler(e){
if(this.value==this.oldvalue)return; //not changed really
this.oldvalue=this.value;
// .... your stuff
}
A quick fix (untested) should be to defer the call to focus() via
setTimeout(function() { ... }, 0);
until after the event handler has terminated.
However, it is possible to make it work without such a hack; jQuery-free example code:
<head>
<style>
input { display: block; }
</style>
<body>
<div></div>
<script>
var div = document.getElementsByTagName('div')[0];
var field = document.createElement('input');
field.type = 'text';
field.onchange = function() {
// only add a new field on change of last field
if(this.num === div.getElementsByTagName('input').length)
div.appendChild(createField(this.num + 1));
this.nextSibling.focus();
};
function createField(num) {
var clone = field.cloneNode(false);
clone.num = num;
clone.onchange = field.onchange;
return clone;
}
div.appendChild(createField(1));
</script>
I can confirm myOnChange gets called twice on Chrome. But the context argument is the initial input field on both calls.
If you remove the alert call it only fires once. If you are using the alert for testing only then try using console instead (although you need to remove it for testing in IE).
EDIT: It seems that the change event fires twice on the enter key. The following adds a condition to check for the existence of the new field.
function myOnChange(context, curNum) {
nextNum = curNum+1;
if ($('#prefix_'+nextNum).length) return false;// added to avoid duplication
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum)[0].focus();
return false;
}
Update:
The $('#prefix_'+nextNum).focus(); does not get called because focus is a method of the dom object, not jQuery. Fixed it with $('#prefix_'+nextNum)[0].focus();.
The problem is indeed that because of the focus(), the onchange is called again. I don't know if this is a good sollution, but this adding this to the function is a quick sollution:
context.onchange = "";
(The onchange is called again, but is now empty. This is also good because this function should never be called twice. There will be some interface changes in the final product that help with problems that would arise from this (mistakes and all), but in the end this is something I probably would have done anyway).
sollution here: http://jsfiddle.net/k4WKH/2/
As #johnhunter says, the focus does not work in the example, but it does in my complete code. I haven't looked into what's going on there, but that seems to be a separate problem.
maybe this some help to anybody, for any reason, in chrome when you attach an event onchage to a input text, when you press the enterkey, the function in the event, do it twice, i solve this problem chaged the event for onkeypress and evaluate the codes, if i have an enter then do the function, cause i only wait for an enterkey user's, that not works for tab key.
input_txt.onkeypress=function(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if(charCode === 13) evaluate( n_rows );
};
Try this example:
var curNum = 1;
function myOnChange( context )
{
curNum++;
$('<input type="text" onchange="return myOnChange( this )" id="prefix_'+ curNum +'" >').insertAfter( context );
$('#prefix_'+ curNum ).focus();
return false;
}
jsFiddle.

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories