document.onkeyup triggers when it shouldn't - javascript

So I have the following code, which should append 'true' to the div "test" every 25ms as long as key 68 (the d key) is being pressed, right?
<html>
<body>
<div id="test"></div>
<script type="text/javascript">
var key=false;
var keyDown=function(e) {
if (e.keyCode==68) {
key=true;
}
}
var keyUp=function(e) {
if (e.keyCode==68) {
key=false;
}
}
document.onkeydown=keyDown;
document.onkeyup=keyUp;
var run=function() {
document.getElementById('test').appendChild(document.createTextNode(key+'\n'));
t = setTimeout('run()', 25);
}
var t = setTimeout('run()', 25);
</script>
</body>
</html>
Save the code, load it in a browser and hold down on the d key. If I'm not crazy, you'll see that it occasionally appends 'false' even though the d key was never released. (I've tried this in FF and Chrome in Linux and Vista). Anybody happen to know why, or have a workaround?
Edit: It seems to behave as expected in FF running in OS X.

I just tried it in IE7. After changing "e.keyCode" to "event.keyCode", it worked just as you expected.
Have you actually tried the code you pasted here, or are you working with other code that may have a bug in it?
Edit
I just ran this in Chrome. Again, it behaves as expected.
Are you using a wireless keyboard that could be susceptible to interference or battery weakness that wouldn't affect normal keyboard use, but becomes visible in this test?

Related

Safari offsetWidth on reload is wrong

The past few weeks I've been working on a website which is live now. It can be seen here: http://www.momkai.com/
This website works fine in all browsers I tested it in except one: Safari. When I open this website in Safari 10.1 and hover over the first paragraph, this is what I see:
This is correct. The first word of each line of text should be underlined. Hovering of the lines results in this styling:
So far everything is going well. Now I reload the page and I see this:
The underlines are way to wide! I've logged the offsetWidths and they are just completely wrong. This is the code which I use to retrieve the widths:
const parentParagraph = this.el.parentNode.parentNode;
let selfIndex;
let siblingUnderlineWidth;
this.underlineWidth = this.el.querySelector('.js-text-block-link-text-highlight').offsetWidth;
this.siblings = [].slice.call(parentParagraph.querySelectorAll('.js-text-block-link-text'));
this.siblingUnderlineWidths = [];
for (let sibling of this.siblings) {
if (sibling.isSameNode(this.underline)) {
selfIndex = this.siblings.indexOf(sibling);
} else {
siblingUnderlineWidth = sibling.querySelector('.js-text-block-link-text-highlight').offsetWidth;
console.log(siblingUnderlineWidth);
this.siblingUnderlineWidths.push(siblingUnderlineWidth);
}
}
this.siblings.splice(selfIndex, 1);
I've also added two screenshots of the console.log's to demonstrate how the values differ:
I'm experiencing this behaviour in Safari 10.1 on desktop and Safari for iOS. I've no idea what's going wrong so I hope someone can help me. Thanks in advance!
I'll be happy to provide more code if required.
I have found that when something CSS changes after I refresh, it is usually a loading order issue.
For example I was using
document.addEventListener('DOMContentLoaded', runsWhenReady);
But sometimes the offsetWidth would be wrong.
Figured out this we because the CSS file wasn't fully loaded, which changes how the offsetWidth is.
Chrome and Safari handle caching differently, which is why it would be different on refresh.
So I switched to:
window.addEventListener('load', runsWhenReady);
Which only fires after everything including CSS is loaded and it solved the issue.

Is it possible to generate a virtual keyboardEvent (tab) in IE8 with Javascript

I want to generate a virtual keyboardEvent(tab). I did some research on the same and got few usefully answers, however it not working for me. I understand that Javascript is event driven programming language so User should press require key, but I also want to understand that can we generate an keyboard event through JavaScript.
function fnGenerateTabKeyEvent() {
var e = document.createEventObject("KeyboardEvent");
e.keyCode = 9; // tab's ASCII
document.getElementsByName("someTxtBox").fireEvent("onkeyup", e);
}
<input type="text" id="someTxtBox"/>
It's not working in IE8 and I'm not getting any error either. I just want that whenever I can this function it should an keyboardevent(tab) from that text box.
Source1,Source2. Any suggestion will be helpful.
I think you were too hasty, as your code works on my machine:
<html>
<body>
<input type="text" id="someTxtBox" onkeyup="window.alert(event.keyCode)"/>
<script type='text/javascript'>
function fnGenerateTabKeyEvent() {
var e = document.createEventObject("KeyboardEvent");
e.keyCode = 9; // tab's ASCII
document.getElementById("someTxtBox").fireEvent("onkeyup", e);
}
fnGenerateTabKeyEvent();
</script>
</body>
</html>
There're of course some "issues" (like - accessing elements via getElementsByName, maybe having the script called before the <input>, but let's blame that on copy-pasting ;)) As such, on my IE, running in document mode 8 the alert successfully displays 9.

How to force Android internet browser to display style changes immediately

I made a simple flashcards HTML application and I experience strange problem with behavior under Android internet browser (default installation) on my Samsung Galaxy Tab2 7.0 tablet. When style of element is changed, such as
$(".question").css('color', '#FFFFFF')
$(".answer").css('color', '#FFFFFF')
$(".tag").css('background-color', '#FFFFFF')
the browser does not make any changes on display immediately. Later in code I am replacing text of containers and calculating sizes to fit text into element. I want this process to be invisible (that's why I want to do this white-on-white). I cannot hide elements, as then calculation would not work.
I have tested this under Windows 7 with Chrome and IE9 and it works great there. So there is some problem with the Android browser. When I put test code alert('debug'); behind the lines above, the Android browser shows message with no changes on colors on elements, but browsers under Windows 7 show message with white-on-white elements as expected.
How can I force Android browser to reflect such style changes immediately? Is there some script function available for that, or some <meta> tag that would fix this? Please advise.
When you say you want to "display style changes immediately" I'm guessing you mean that your script is going to continue to execute and you want the screen to update.
You need to use continuations. Rather than letting your script keep executing you need to yield and continue. You do this by breaking up your code into multiple functions and each piece finishes by setting a timeout for the next piece. Here's a simple example. When this is done with a loop, all the x's appear at once. When using continuations, one x appears at a time.
<html>
<script>
function using_a_loop() {
var e = document.getElementById('spot');
for (var i = 0; i < 1000; ++i) {
e.innerText += ' x';
}
}
function using_continuations(i) {
var e = document.getElementById('spot');
i = i || 0; // start at 0 when i not provided
e.innerText += ' x';
++i;
if (i < 1000) {
setTimeout(function() { using_continuations(i); }, 0);
}
}
</script>
<div id="spot">X marks the spot:</div>
<button onclick="using_a_loop()">use a loop</button>
<button onclick="using_continuations()">use continuations</button>
</html>

Print section of page script works perfectly in IE but problems in Firefox

In my battles to find a solution to printing just one area of the page that works within WordPress, I came across an excellent little script that meets my needs perfectly.. but only in IE browser. For some reason Firefox doesn't want to play ball.
The script is:
function printURL(sHref) {
if(document.getElementById && document.all && sHref) {
if(!self.oPrintElm) {
var aHeads = document.getElementsByTagName('HEAD');
if(!aHeads || !aHeads.length)
return false;
if(!self.oPrintElm)
self.oPrintElm = document.createElement('LINK');
self.oPrintElm.rel = 'alternate';
self.oPrintElm.media = 'print';
aHeads[0].appendChild(self.oPrintElm);
}
self.oPrintElm.href = sHref;
self.focus();
self.print();
return true;
}
else
return false;
}
Called by:
<a onclick="printURL(this.href); return false;" href="http://printstuff.com" target="_blank">print</a>
This is working in IE, but not FF. I don't know much about JavaScript, so would appreciate if you could tell me if there's anything you see that's giving Firefox headaches.
By the way - I have to go a javascript route instead of using a print CSS file, as the area I want to print (a coupon) is set in a table which is obviously set in the WordPress theme's container and wrapper divs which makes it difficult to isolate it for printing.
I've also experimented with iframe printing, which I made some headway with, but IE gives me problems there (rolleyes). So this script above seems a good answer to me, except Firefox does nothing when I click 'print'. Thanks a lot.
document.all tests false in all browsers other than IE. So your code is very explicitly only running the self.print() line in IE only.

Mobile minibrowser: how to reload image while maintaing page offset position?

In mobile web minibrowsers, it seems that the window object makes no sense — since there's only one window to show. Therefore, things like window.pageYOffset=320 make no sense (as far as I can tell).
Given a simple example such as a map zoomin/zoomout such as
<html>
<head>
<title>zoom.html</title>
<script language="javascript">
var zoom=15;
var vpos=window.pageYOffset;
var key="whatever-your-Google-Maps-site-key-is";
function setImgSrc(z) {
document.getElementById('img').src=
"http://maps.google.com/maps/api/staticmap?center=Lisbon,Portugal&zoom="
+zoom+"&size=400x400&maptype=roadmap&sensor=false&key="+key;
}
function zoomin()
{ if(zoom<=18) zoom++; vpos=window.pageYOffset; setImgSrc(zoom); }
function zoomout()
{ if(zoom>=1) zoom--; vpos=window.pageYOffset; setImgSrc(zoom); }
</script>
</head>
<body onload="javascript:setImgSrc(15);">
<h1>zoom</h1>
<p><img id="img" alt="Lisbon,Portugal"/></p><p>
<a onclick="javascript:zoomin()">[+]</a>
<a onclick="javascript:zoomout()">[–</a>
</p><hr></body></html>
which seems to work well on desktop browsers; so I ask: how can I indicate that, on updating the page (onclick doesn't seem to work on minibrowsers, but href does) it should offset the page to the previous position?
(For other reasons, simply (re)loading the page to a given named anchor isn't working on the problem I'm dealing with.)
Thanks in advance for your feedback.
Isn't it lovely when you answer your own questions? Hmmm...
Anyway, according to this, some properties/functions for the JavaScript (JScript?) window object have different representations according to the choice of browser (Firefox, IE, etc.). Therefore, a possible page vertical offset function would be
function setPageVPos(w,vpos) {
try { w.scrollTo(0,vpos); } catch(e) {}
try { w.document.body.scrollTop(vpos); } catch(e) {}
}
The first tries with the window.scrollTo implementation in Firefox browsers, and the second tries with the document.body.scrollTop implementation in IE browsers. I've tested in both Firefox (desktop) browser and in a HP iPaq IE-like (mobile) minibrowser and works on both.

Categories