I've try to use code from this question: How to detect `focusin` support?
but for Chromium that supports offline event hasEvent('offline') return false. Anybody know how to detect offline/online events in JavaScript?
You can try
'onoffline' in window
or
'onoffline' in document.body
It seems that online and offline events start on body and bubble up so you can't use div to detect it. But I've created this code:
var body = document.getElementsByTagName('body')[0];
body.setAttribute('ononline', 'return;')
typeof body.ononline == 'function';
Try:
return !!window.applicationCache;
If I understand properly your question, you also may want to read this article.
EDIT:
Basically you can use the following function:
function reportConnectionEvent(e)
{
if (!e) e = window.event;
if ('online' == e.type) {
alert( 'The browser is ONLINE.' );
}
else if ('offline' == e.type) {
alert( 'The browser is OFFLINE.' );
}
else {
alert( 'Unexpected event: ' + e.type );
}
}
window.onload = function() {
document.body.ononline = reportConnectionEvent;
document.body.onoffline = reportConnectionEvent;
}
Also you may check this for demo http://html5demos.com/offline-events
Related
I have created a simple code to handle keypress event:
var counter = 0;
$('input').on('keypress', function () {
$('div').text('key pressed ' + ++counter);
});
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+).
What could be the issue?
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup event:
// JavaScript:
var counter = 0;
document.querySelector('input').addEventListener('keyup', function () {
document.querySelector('div').textContent = `key up ${++counter}`;
});
// jQuery:
var counter = 0;
$('input').on('keyup', function () {
$('div').text('key up ' + ++counter);
});
Use jQuery's input event, like this:
$( 'input' ).on( 'input', function() {
...
} );
With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/
$(document).ready(function() {
var pattForZip = /[0-9]/;
$('#id').on('keypress input', function(event) {
if(event.type == "keypress") {
if(pattForZip.test(event.key)) {
return true;
}
return false;
}
if(event.type == 'input') {
var bufferValue = $(this).val().replace(/\D/g,'');
$(this).val(bufferValue);
}
})
})
Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.
Eg:
function getKeyCode(str) {
return str && str.charCodeAt(0);
}
function keyUp(){
var keyCode = getKeyCode("1");
}
I think it is bad idea to use other events in place of 'keypress'.
What you need to do is just include a jQuery file into your project.
A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.
You can download it from : https://jquerymobile.com/download/
I'm trying to learn Javascript before I learn jQuery so I can get the foundation down before moving up.
To learn, I've made a simple guessing game that works in Chrome & Safari, but not Firefox. (I guess that is why people use jQuery!).
I adjusted the code based on this answer. But it is still not working in Firefox. Here's the relevant code. Any ideas?
function reportAnswer(e) {
if(!e) e = window.event;
questionNumber++;
document.getElementById("myCount").innerHTML = (questionNumber + 1);
var x = e.target || e.srcElement;
checkAnswer();
}
function checkAnswer() {
var thisAnswer = questionDatabase[currentQuestion].answer;
if(event.target.id == thisAnswer) {
document.getElementById("answer").innerHTML = ("YES! </br>" + questionDatabase[currentQuestion].photo);
score++;
}
else {
document.getElementById("answer").innerHTML = ("<img src=http://philly.barstoolsports.com/files/2012/11/family-feud-x2.png width='370' height='370'>");
}
}
Your checkAnswer function uses the nonstandard global window.event. You want to do two things:
Add an event or e argument to it like #thesystem suggests.
Make sure to pass that argument in from whatever your event handler is.
I'm trying to code a simple form with file upload which targets the iFrame. I've got it pretty much covered, but Internet Explorer does not support load method on dynamically generated iFrames so I need to do an alternative approach for it. My question is - what's the best and most accurate (plus light) way of identifying the browser type using Javascript?
I know that Modernizr can check for specific methods / properties, but not quite sure if it could help in this specific scenario. It has Modernizr.hasEvent(), but I can't use it to check the dynamically created elements.
The easiest way to check this, to my mind would be:
if ('onload' in iFrameVar)
{
console.log('your code here');
}
Where iFrameVar is a reference to an iframe, of course:
function elemSupportsEvent(elem,e)
{
var f = document.createElement(elem);
if (e in f)
{
console.log(elem + ' supports the '+ e + ' event');
return true;
}
console.log(elem + ' doesn\'t support the '+ e + ' event');
return false;
}
elemSupportsEvent('iframe','onload');//logs "iframe supports the onload event" in chrome and IE8
Just a quick fiddle by means of example of how you can use a function to check event support on various elements.
In response to your comment: if you want to check for dynamic content -as in ajax replies- you could simply use the readystatechange event:
xhr.onreadystatechange = function()
{
if (this.readyState === 4 && this.status === 200)
{
var parent = document.getElementById('targetContainerId');//suppose you're injecting the html here:
parent.innerHTML += this.responseText;//append HTML
onloadCallback.apply(parent,[this]);//call handler, with parent element as context, pass xhr object as argument
}
};
function onloadCallback(xhr)
{
//this === parent, so this.id === 'targetContainerId'
//xhr.responseText === appended HTML, xhr.status === 200 etc...
alert('additional content was loaded in the '+ this.tagName.toLowerCase+'#'+this.id);
//alerts "additional content was loaded in the div/iframe/td/whatever#targetContainerID"
}
if you want to check support for particular event, you can try something like this :
var isEventSupported = (function(){
var TAGNAMES = {
'select':'input','change':'input',
'submit':'form','reset':'form',
'error':'img','load':'img','abort':'img'
}
function isEventSupported(eventName) {
var el = document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
return isEventSupported;
})();
here is a live demo for the above :
http://kangax.github.com/iseventsupported/
Use navigator.userAgent. It contains browser user agent
if (navigator.userAgent.search("MSIE 6") == -1){
// We've got IE.
}
Apologize if this is answered already. Went through some of the related questions and google, but ultimately failed to see why this isn't working.
My code is as follows
<iframe id="editor"></iframe>
editorWindow = document.getElementById('editor').contentWindow;
isCtrlDown = false;
function loadEditor()
{
editorWindow.document.designMode = "on";
editorWindow.document.onkeyup = function(e) {
if (e.which == 91) isCtrlDown = false;
}
editorWindow.document.onkeydown = handleKeyDown;
}
function handleKeyDown(e)
{
if (e.which == 91) isCtrlDown = true;
if (e.which == 66 && isCtrlDown) editFont('bold');
if (e.which == 73 && isCtrlDown) editFont('italic');
}
function editFont(a,b)
{
editorWindow.document.execCommand(a,false,b);
editorWindow.focus();
}
This code works perfectly in Chrome, but the keyboard shortcuts do not work in Firefox. In fact, in Firefox it does not seem to register the events for keyup/keydown at all.
Am I doing something grossly wrong here that is mucking up Firefox?
For editable documents, you need to use addEventListener to attach key events rather than DOM0 event handler properties:
editorWindow.document.addEventListener("keydown", handleKeyDown, false);
If you care about IE 6-8, you will need to test for the existence addEventListener and add the attachEvent equivalent if it is missing.
Try using:
editorWindow = document.getElementById('editor').frameElement;
I'm not sure this will solve the issue, it may also be:
editorWindow = document.getElementById('editor').contentDocument;
Or even possibly:
editorWindow = document.getElementById('editor').frameElement.contentDocument;
One thing you can do is put the entire string in a try statement to catch any errors and see if the content is being grabbed from within the iframe.
try { editorWindow = document.getElementById('editor').contentWindow; } catch(e) { alert(e) };
The only other thought I have is that you're typing into a textbox which is within an iframe, and you may possibly have to add the onkeydown event to that specific item, such as:
var editorWindow = document.getElementById('editor').contentDocument;
var textbox = editorWindow.getElementById('my_textbox');
function loadEditor()
{
editorWindow.document.designMode = "on";
textbox.onkeydown = function(e) {
alert('hello there');
}
}
I hope one of these is the solution. I often find when it comes to cross-platform functionality it often boils down to a little trial and error.
Good Luck!
I'm having troubles getting the attachEvent to work. In all browsers that support the addEventListener handler the code below works like a charm, but in IE is a complete disaster. They have their own (incomplete) variation of it called attachEvent.
Now here's the deal. How do I get the attachEvent to work in the same way addEventListener does?
Here's the code:
function aFunction(idname)
{
document.writeln('<iframe id="'+idname+'"></iframe>');
var Editor = document.getElementById(idname).contentWindow.document;
/* Some other code */
if (Editor.attachEvent)
{
document.writeln('<textarea id="'+this.idname+'" name="' + this.idname + '" style="display:none">'+this.html+'</textarea>');
Editor.attachEvent("onkeyup", KeyBoardHandler);
}
else
{
document.writeln('<textarea id="hdn'+this.idname+'" name="' + this.idname + '" style="display:block">'+this.html+'</textarea>');
Editor.addEventListener("keyup", KeyBoardHandler, true);
}
}
This calls the function KeyBoardHandler that looks like this:
function KeyBoardHandler(Event, keyEventArgs) {
if (Event.keyCode == 13) {
Event.target.ownerDocument.execCommand("inserthtml",false,'<br />');
Event.returnValue = false;
}
/* more code */
}
I don't want to use any frameworks because A) I'm trying to learn and understand something, and B) any framework is just an overload of code I'm nog going to use.
Any help is highly appreciated!
Here's how to make this work cross-browser, just for reference though.
var myFunction=function(){
//do something here
}
var el=document.getElementById('myId');
if (el.addEventListener) {
el.addEventListener('mouseover',myFunction,false);
el.addEventListener('mouseout',myFunction,false);
} else if(el.attachEvent) {
el.attachEvent('onmouseover',myFunction);
el.attachEvent('onmouseout',myFunction);
} else {
el.onmouseover = myFunction;
el.onmouseout = myFunction;
}
ref: http://jquerydojo.blogspot.com/2012/12/javascript-dom-addeventlistener-and.html
The source of your problems is the KeyBoardHandler function. Specifically, in IE Event objects do not have a target property: the equivalent is srcElement. Also, the returnValue property of Event objects is IE-only. You want the preventDefault() method in other browsers.
function KeyBoardHandler(evt, keyEventArgs) {
if (evt.keyCode == 13) {
var target = evt.target || evt.srcElement;
target.ownerDocument.execCommand("inserthtml",false,'<br />');
if (typeof evt.preventDefault != "undefined") {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
/* more code */
}
Just use a framework like jQuery or prototype. That's what they are there for, this exact reason: being able to do this sort of thing w/out having to worry about cross-browser compatibility. It's super easy to install...just include a .js script and add a line of code...
(edited just for you Crescent Fresh)
With a framework, the code is as simple as...
<script type='text/javascript' src='jquery.js'></script>
$('element').keyup(function() {
// stuff to happen on event here
});
Here is a function I use for both browsers:
function eventListen(t, fn, o) {
o = o || window;
var e = t+Math.round(Math.random()*99999999);
if ( o.attachEvent ) {
o['e'+e] = fn;
o[e] = function(){
o['e'+e]( window.event );
};
o.attachEvent( 'on'+t, o[e] );
}else{
o.addEventListener( t, fn, false );
}
}
And you can use it like:
eventListen('keyup', function(ev){
if (ev.keyCode === 13){
...
}
...
}, Editor)
Different browsers will process events differently. Some browsers have event bubble up throw the controls where as some go top down. For more information on that take a look at this W3C doc: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
As for this specific issue setting the "userCapture" parameter to false for the addEventListener will make events behave the same as Internet Explorer: https://developer.mozilla.org/en/DOM/element.addEventListener#Internet_Explorer
You might be better off using a JavaScript framework such as MooTools or jQuery of your choice to ease cross-browser support. For details, see also
http://mootools.net/docs/core/Element/Element.Event
http://api.jquery.com/category/events/
MooTools port of parts of your sample code:
var Editor = $(idname).contentWindow.document;
...
$(document.body).grab(new Element('textarea', {
'id' : this.idname,
'name' : this.idname,
'style': 'display:none;',
'html' : this.html
});
Editor.addEvent('keyup', KeyBoardHandler);
By the way, is it on purpose that you use both idname and this.idname in the code above ?