Some Javascript is not working until hitting F12 in IE 11 - javascript

The Javascript code is working correctly in Firefox and Chrome, but for IE(I am using 11),it's not working until I hit F12 for debugging. And there is also no error displayed in debugger in IE. Any idea why?
The first function is to check if the browser support classList or not, apparently, IE doesn't support it. Here is the code:
function checkClassListSupport() {
var supportsClassList = ({}).toString.call(document.body.classList) == "[object DOMTokenList]";
return supportsClassList;
}

It's working now if I remove the console.log code, or change the document module to "Edge".

Related

window.open returns null or undefined in edge browser

i am doing some operation with the window object returned from open method.
in all other browsers it is working even in other IE browsers but not working in edge browser,can any one please tell me the reason for this and provide solution
this is the code that i have written
var mywindow= window.open(url,'test', '_blank');
if ((mywindow== null||typeof(mywindow) == "undefined")
{
//here i am showing alert
}

Invalid calling object IE

In FF and Chrome i can set the this value to the location object using bind, with the following code
locationFacade ={
reload: location.reload.bind(location)
}
locationFacade.reload();
Or I can use apply
locationFacade ={
reload: function(){
location.reload.apply(location,arguments); }
}
locationFacade.reload();
However in IE 9 I keep getting "Invalid calling object" when calling locationFacade.reload(); I havent tested every IE but issue happens in IE 11 also. Apply and bind are both supported in IE here and here
This problem seems to be a bug of IE. I tested lots of functions in IE11 (document.writeln, window.alert, etc.), and all of them could be bound, except the members of location. This workaround might help:
locationFacade = {
reload: window.navigate ?
window.navigate.bind(window, location.href) :
location.reload.bind(location)
}

valueOf() gives different values in script and F12 console (Chrome and IE11 only)

Here is a simple fiddle:
alert(document.doctype.valueOf())
It produces [object DocumentType], as expected.
However, when I hit F12 and just type document.doctype.valueOf() in the JavaScript console (Chrome, IE11), I see:
<!DOCTYPE html>
Why is the discrepancy, and what property (if any) does it actually show in the console mode?
[UPDATE] When I mentioned that document.doctype.outerHTML used to work until IE11 in the comments to #BlueSkies's answer, I was not quite correct. In my case, I host a WinForms version of IE WebBrowser control in a C# app. I've just discovered it works like this, in IE11 too:
dynamic domDocument = webBrowser.Document.DomDocument;
// this shows '<!DOCTYPE html PUBLIC "" "">'
string doctype = domDocument.doctype.outerHTML;
MessageBox.Show(doctype);
// this shows 'undefined'
domDocument.parentWindow.execScript("alert(document.doctype.outerHTML)");
Apparently, it works from outside, but not from inside the page. Interesting, but unreliable. I guess I should not use document.doctype.outerHTML even in this IE-based app.
The .valueOf() returns neither output. What it returns is the actual node.
So the alert() is giving you the .toString() of the node, and the Chrome/IE consoles have simply decided to serialize the node to HTML.
document.doctype.valueOf() === document.doctype; // true
Here's a little experiment...
document.doctype.toString = function() { return "foobar"; }
alert(document.doctype.valueOf()); // shows "foobar"

JQuery not loading in IE9 down

My site is http://www.thetruenorth.co.uk/
I can't get JQuery to work on my site in IE9 down. It works fine in every other browser.
I've realised that it is the code below, which detects if it's a small screen (mobile), that stops it from working. If I remove this bit, everything works. I use this because I don't know how else I'd disable JS for mobiles, but keep it for desktop. Suggestions welcome.
$(document).ready(function(){
if(matchMedia('only screen and (max-width: 1023px)').matches)
{}
else {
CODE HERE
}
});
I have a feeling there's a bug or something that I'm not aware of. Please could someone put me out of my misery?
Thanks
Simple Debugging in IE9
Open IE9
Press F12 to open the Developer window
Click the 'Script' tab
Click 'Console' on the right pane
Attempt to load your page
You will see the following error:
SCRIPT5009: 'matchMedia' is undefined
scripts.js, line 2 character 2
IE9 does not support the 'matchMedia' function and thus does not define it. Attempting to reference it in code stops the execution of the JavaScript completely at that point because it doesn't know what to do with a reference to something that is undefined.
What is going on
jQuery is loading on your page. You can confirm this by typing '$' into the text input line below the console output and press enter. The console will output some data about how $ is defined. This is a very good sign that jQuery loaded. It isn't conclusive in all situations, but for this one we are set.
What is happening is that your callback that is running onDomReady (via $(document).ready(...)), but it is erroring on the very first line. This error causes the rest of the callback to not execute.
Verifying Functionality Support
You can use caniuse.com to check to see what browsers support functionality (JS, CSS, etc). In this case: http://caniuse.com/matchmedia. You will note that IE10 is the first version that supports the matchMedia function. You can assume that in any earlier version you will not have matchMedia by default and referencing it will cause errors.
What You Can Do Now
On the caniuse.com site, at the top is a horizontal list titled "Resources". In this area you will generally find ways to patch browsers that do not support specific functionality.
In the case of matchMedia there is a link to a 'polyfill' which will use custom js to emulate the functionality of matchMedia. The url is: https://github.com/paulirish/matchMedia.js/.
Polyfills sometimes have limitations or catches to using them so be careful. It is also interesting to note that the matchMedia polyfill was written by Paul Irish, who is a very public figure for web technologies.
A Note On Conditional IE Includes
IE supports conditional comments, so you can include the polyfill defined above only for specific versions of IE; in your case anything < IE10. This is documented on the MDN here: http://msdn.microsoft.com/library/ms537512.aspx
<!--[if lte IE 10]]>
<script src="polyfill.js"></script>
<![endif]-->
This is done so that we can use the browser's implementation when possible (generally faster and potentially with more functionality) and polyfill only when needed.
j08691 found the problem you have.
If you need matchMedia to work with IE9 and down, or Firefox 6 and down or Safari 5.1 and down you must shim it. Here is a polyfill for matchMedia which will let you use it on older browsers.
Note, this is not a jQuery issue, this issue is with matchMedia browser support
That's because matchMedia only works with IE10.
Ref: https://developer.mozilla.org/en-US/docs/DOM/window.matchMedia
You may be better off doing this with PHP. ie probably isn't able to run matchMedia correctly. I always keep things like that on the server side because that'll run the same for any client. If you're using PHP try get_browser(). Really easy to write a quick if statement. Check the examples if you need help.
Andrew Martinez's answer is fairly thorough and correct, and I personally found it to be very useful.
The markup for getting the matchMedia method in IE9 would look as follows
<![if lt IE 10]>
<script src="scripts/matchMedia.js"></script>
<![endif]>
I just check if the browser is Chrome or not and then add the matchMedia code from github, have a look below:
$(document).ready(function() {
var isChrome = !!window.chrome;
if (isChrome == true) {
//do this for chrome
} else if (isChrome != true) {
//do this for all other browsers including IE
//so copy and paste current matchMedia.js script form here https://github.com/paulirish/matchMedia.js/blob/master/matchMedia.js like below
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */
window.matchMedia || (window.matchMedia = function() {
"use strict";
// For browsers that support matchMedium api such as IE 9 and webkit
var styleMedia = (window.styleMedia || window.media);
// For those that don't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
script = document.getElementsByTagName('script')[0],
info = null;
style.type = 'text/css';
style.id = 'matchmediajs-test';
script.parentNode.insertBefore(style, script);
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;
styleMedia = {
matchMedium: function(media) {
var text = '#media ' + media + '{ #matchmediajs-test { width: 1px; } }';
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
// Test if media query is true or false
return info.width === '1px';
}
};
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
};
}());
//below you can add your own matchMedia code
}
});

"'localStorage' is null or not an object" Error in IE8

I have this string which i'm trying to store and get to localStorage, and retrieve from it so it could show.
Here's my code:
var datas = new Array;
if (navigator.appName !== 'Microsoft Internet Explorer'){
var qsVal = document.getElementsByClassName("val");
}
else{
var qsVal = document.querySelectorAll('.val');
}
if (navigator.appName !== 'Microsoft Internet Explorer'){
var qsKey = document.getElementsByClassName("key");
}
else{
var qsKey = document.querySelectorAll('.key');
}
var storedPlays;
var stuff = document.getElementById("stuff");
function pushArray(){
for (var i=0, len = qsVal.length; i < len; i++){
thisValue = qsVal[i].value;
thisKey = qsKey[i].value;
datas.push([thisValue,thisKey]);
}
localStorage.setItem('datas', JSON.stringify(datas));
}
function showStuff(){
storedPlays = JSON.parse(localStorage.getItem('datas'));
document.getElementById("stuff").innerHTML = storedPlays;
}
It works great with FF and Chrome, but IE8 returns "'localStorage' is null or not an object" when I call 'showStuff'.
What's interesting is that it doesn't give me an error when I call 'pushArray', which uses 'localStorage' as well.
Iv'e also tried using "window.localStorage" instead of just "localStorage", it returned the same error...
IE8 is supposed to support localStorage, according to Microsoft and W3, so does anyone has any clue as to where the problem is?
Thanks a million!
EDIT - This is a jsfiddle for the code. for some reason, it doesn't work that good but just to give you a feel of the code...
As per my understanding IE8 give storage to only valid domains. Try placing your example in some Web-server it should resolve the issue.
I faced the same issue when I tested it as an individual file but when i placed it in a server(Tomcat in my case) it just worked fine.
Check if you are actually in IE 8 mode - as opposed to quirks or IE 7 mode. Fastest way to do this is hit F12 to bring up the dev tools, and the browser mode is listed on the upper right of that tab.
I would give using window.localStorage as shot. See Introduction to Web Storage for IE
Can you open the developer tools in IE and check that typeof json. stringify and json.parse are functions and also localstorage. I am not sure whether native JSON exist on IE.
Also why are you setting the object inside the loop, shouldnt it be outside it?
[Edit]
Added this fiddle for your code jsfiddle.net/yrhdN/2 and everything seems to work fine. I have tested in IE9 under IE8 compatibility mode)
[Edit]
One more thing about this code, it seems innerHtml in showStuff() doesn't work with a paragraph. Changing the html from p to div and using innerText makes things a little better:
<div id="stuff">
</div>
function showStuff(){
var storedPlays = JSON.parse(localStorage.getItem('datas'));
document.getElementById("stuff").innerText = storedPlays;
}
This seems to happen only in IE. Here is an updated fiddle: http://jsfiddle.net/yrhdN/7/
Try this also if you do not wish any local server application to shoot the webpage.
Look for the code in your script : window['localStorage'] !== null
change it to : window['localStorage'] != null
It worked in my case.

Categories