Check translate3d support not working when loading script in body - javascript

This proposed solution seems to work quite well in most scenarios but I noticed it fails to detect support for translate3d properties when a <script> tag is used within the <body>.
Reproduction online
This is the function used to detect the 3d support:
function has3d() {
if (!window.getComputedStyle) {
return false;
}
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform':'-webkit-transform',
'OTransform':'-o-transform',
'msTransform':'-ms-transform',
'MozTransform':'-moz-transform',
'transform':'transform'
};
// Add it to the body to get the computed style.
document.body.insertBefore(el, null);
for (var t in transforms) {
if (el.style[t] !== undefined) {
el.style[t] = "translate3d(1px,1px,1px)";
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}

Related

Is there a way to trigger a function when a user tries to print in angular?

I am using a print element function to print out a view in my SPA. When the view changes the function runs and grabs the view. However, if the user changes something on the page it will not update and when you try to print, you get the same view as it was when the page first loaded. This is the function I'm using:
var printElement = function (elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
$printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof (delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof (delimiter) === "object") {
$printSection.appendChlid(delimiter);
}
}
$printSection.appendChild(domClone);
};
My question is, can I trigger this function when someone uses the browser print function, such as Ctrl+P so that when they go to print the page, it will be updated?
You can make use of the default javascript events. Since you mentioned you are using jQuery:
$(document).bind("keydown keyup", function(e){
if(event.ctrlKey && event.keyCode == 80){
// CTRL+P was pressed.
}
});
I found a solution to my problem, it was answered by another question on stack overflow detect print. This is what I did:
var beforePrint = function () {
printElement(document.getElementById("print"));
};
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
printElement(document.getElementById("print"));
}
});
printElement(document.getElementById("print"));
window.onbeforeprint = beforePrint;
This covers IE, Chrome, Firefox, and Safari. The beforePrint works for IE and Firefox and matchMedia works for Safari and Chrome.

Change element display none back to default style value JS

I have a function in JS that hides the element parsed:
function hide(id){
document.getElementById(id).style.display = "none";
}
How can I create a function that brings back the element to the default style value. For instance a div display property is "block" as for an image is "inline-block", other elements are "inline" or lists are "list-item" How can I bring them back their default state?
function show(id){
document.getElementById(id).style.display = "?????";
}
I know how to do it in Jquery but it is not an option.
In CSS there might be styles for the elements including style:none, which need to be overwritten to the default value.
Since there is CSS in my example making style.display = '' eliminates the style added with JS but gets back to whatever style is added in CSS, I want to bring it back to its default value even before assigning styles with CSS.
I tried this as it was suggested in a link in one of the comments:
elem = document.getElementById(id);
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("display");
but in this case 'theCSSprop' returns "none" for a div, when I expect "block"
Any ideas?
Thanks.
You need just assign it to empty value:
document.getElementById(id).style.display = "";
Or using removeProperty method:
document.getElementById(id).style.removeProperty( 'display' );
But note that removeProperty will not work on IE<9.
If you want to get original CSS value you will need probably to get it from empty <iframe> element. I created example on jsFiddle how to get current value using getComputedStyle and iframe value on jsFiddle.
Please note that getComputedStyle not support old versions of IE. It support IE9+.
For IE8 you should use Element.currentStyle
Note:
If you define display:none; for a class or tag (either in a separate css file or in the head section), the above methods won't work.
Then you will have to determine which type of tag + class it is and manually assign the value specific to it.
These are examples of what may not work:
// In many cases this won't work:
function ShowHide_WillRarelyWork(id, bDisplay) {
// Note: This will fail if parent is of other tag than element.
var o = document.getElementById(id);
if (o == null) return;
//
if (bDisplay) {
o.style.display = 'inherit';
o.style.visibility = true;
}
else {
o.style.display = 'none';
}
} // ShowHide_WillRarelyWork(...)
// This will work in most, but not all, cases:
function ShowHide_MayWork(id, bDisplay) {
// Note: This will fail if element is declared as 'none' in css.
var o = document.getElementById(id);
if (o == null) return;
//
if (bDisplay) {
o.style.display = null;
o.style.visibility = true;
}
else {
o.style.display = 'none';
}
} // ShowHide_MayWork(...)
This is long but will most probably work:
function getDefaultDisplayByTag(sTag) {
// This is not fully implemented, as that would be very long...
// See http://www.w3.org/TR/CSS21/sample.html for full list.
switch (sTag) {
case 'div':
case 'ul':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6': return 'block';
//
case 'li': return 'list-item';
//
case 'table': return 'table';
//
case 'td':
case 'th': return 'table-cell';
}
// Fallback:
return 'block';
} // getDefaultDisplayByTag(...)
//
function computeDisplay(o) {
var oFunction = window.getComputedStyle;
if (oFunction) {
var oStyle = window.getComputedStyle(o)
if ((oStyle) && (oStyle.getPropertyValue)) {
return oStyle.getPropertyValue('display');
}
}
if (window.currentStyle) {
return window.currentStyle.display;
}
return null; // <-- This is going to be a bad day...
} // computeStyle(...)
//
// This will most probably work:
function ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive) {
if ((o == null) || (o == undefined) || (o == document) || (o.tagName == undefined)) return;
//
if (bDisplay == null) bDisplay = true
if (!bDisplay) {
o.style.display = 'none';
}
else {
// First remove any directly set display:none;
if ((o.style.display == 'none') || (o.style.display == '')) {
o.style.display = null;
}
//
var sDisplay = null;
var sDisplayCurrent = computeDisplay(o);
var oParent = o.parentNode;
// Was this element hidden via css?
if ((sDisplayCurrent == null) || (sDisplayCurrent == 'none')) {
// We must determing a sensible display value:
var sTag = o.tagName;
sDisplay = getDefaultDisplayByTag(sTag);
} // else: if ((sDisplayCurrent != null) && (sDisplayCurrent != 'none'))
//
// Make sure visibility is also on:
if (sDisplay != null) o.style.display = sDisplay;
o.style.visibility = true;
//
if (bMaybeRecursive) {
// We should travel up the tree and make sure parent are also displayed:
ShowHideObject_WillProbablyWork(oParent, true, true);
}
} // else: if (!bDisplay) ...
//
} // ShowHideObject_WillProbablyWork(...)
//
// ... and finally:
function ShowHideId_WillProbablyWork(id, bDisplay, bMaybeRecursive)
var o = document.getElementById(id);
ShowHideObject_WillProbablyWork(o, bDisplay, bMaybeRecursive)
} // ShowHideId_WillProbablyWork(...)
Of course this could be shortened a bit; but that's how it looks in my source.
Here is one more solution for retrieving any property default value of any element. Idea is following:
Get nodeName of specific element
Append a fake element of the same node name to body
Get any property value of the fake element.
Remove fake element.
function getDefaultValue(element, property) {
var elDefault = document.createElement(element.nodeName);
document.body.appendChild(elDefault);
propertyValue = window.getComputedStyle(elDefault,null).getPropertyValue(property);
document.body.removeChild(elDefault);
return propertyValue;
}
function resetPropertyValue (element,propertyName) {
var propertyDefaultValue = getDefaultValue(element, propertyName);
if (element.style.setProperty) {
element.style.setProperty (propertyName, propertyDefaultValue, null);
}
else {
element.style.setAttribute (propertyName, propertyDefaultValue);
}
}
#d {
background: teal;
display: inline;
}
<button onclick="resetPropertyValue(document.getElementById('d'), 'display')">Try it</button>
<div id="d">test</div>
You can use custom attributes
function hide(id){
var elem = document.getElementById(id);
//Store prev value
elem.setAttribute('custom-attr', elem.style.display);
elem.style.display = "none";
}
function show(id){
var elem = document.getElementById(id);
//Set prev value
elem.style.display = elem.getAttribute('custom-attr');
}
Filling in an empty value removes the inline override, so the original value is active again.
function show(id){
document.getElementById(id).style.display = "";
}
Since what you want is the default value for the element and not what's in the style sheet, you simply want to set the value to auto.
document.getElementById(id).style.display="auto"
This tells the browser to calculate what the normal display for this type of element is and to use that.

How to tell if only one finger touching in Microsoft IE10

We are emulating scrolling of an infinite list and we wish to detect the difference between a single finger scrolling, or the user starting a gesture.
In theory one can keep a count of fingers down in IE10 by +1 for every MSPointerDown and -1 for MSPointerUp events (and/or matching fingers using the event.msPointerId).
In practice, there is at least one bug where IE10 will generate an MSPointerDown event but never ever send the matching MSPointerUp event. (Sorry, I haven't been able to create a simple test case to show this, but I did spend a lot of time checking that the MSPointerUp event is definitely missing. Maybe due to removal of child elements during the touch).
Perhaps use the MSGesture events to see if multiple fingers are down? (I tried this with little success, but maybe someone else has solved it).
Any ideas?
PS: In webkit the equivalent is to check event.touches.length === 1 in the touchstart event (beware that you need an unobvious trick to get this working: document.ontouchstart must have an event registered, and then event.touches.length will be correct for touchstart events registered on other elements).
Make sure you are also keeping track of MSPointerOut. I've found that MSPointerUp will not be called if you let go of the screen whilst outside of the trackable area.
If it helps, I've got a WinJS class I've been using to track multitouch state.
var TouchState = WinJS.Class.define(
function () {
this.pointers = [];
this.primaryPointerId = 0;
this.touchzones = [];
}, {
touchHandler: function (eventType, e) {
if (eventType == "MSPointerDown") {
if (!this.pointers[this.primaryPointerId] || !this.pointers[this.primaryPointerId].touching) {
this.primaryPointerId = e.pointerId;
}
e.target.msSetPointerCapture(e.pointerId);
this.pointers[e.pointerId] = {
touching: true,
coords: {
x: e.currentPoint.rawPosition.x,
y: e.currentPoint.rawPosition.y
}
};
this.checkTouchZones(this.pointers[e.pointerId].coords.x, this.pointers[e.pointerId].coords.y, e);
}
else if (eventType == "MSPointerMove") {
if (this.pointers[e.pointerId]) {
this.pointers[e.pointerId].coords.x = e.currentPoint.rawPosition.x;
this.pointers[e.pointerId].coords.y = e.currentPoint.rawPosition.y;
}
}
else if (eventType == "MSPointerUp") {
if (this.pointers[e.pointerId]) {
this.pointers[e.pointerId].touching = false;
this.pointers[e.pointerId].coords.x = e.currentPoint.rawPosition.x;
this.pointers[e.pointerId].coords.y = e.currentPoint.rawPosition.y;
}
}
else if (eventType == "MSPointerOut") {
if (this.pointers[e.pointerId]) {
this.pointers[e.pointerId].touching = false;
this.pointers[e.pointerId].coords.x = e.currentPoint.rawPosition.x;
this.pointers[e.pointerId].coords.y = e.currentPoint.rawPosition.y;
}
}
},
checkTouchZones: function (x, y, e) {
for (var zoneIndex in this.touchzones) {
var zone = this.touchzones[zoneIndex];
if (x >= zone.hitzone.x1 && x < zone.hitzone.x2 && y > zone.hitzone.y1 && y < zone.hitzone.y2) {
zone.callback(e);
}
}
},
addTouchZone: function (id, hitzone, callback) {
this.touchzones[id] = {
hitzone: hitzone,
callback: callback
};
},
removeTouchZone: function (id) {
this.touchzones[id] = null;
}
});

Basic Js function to scale two DIV's heights

I want #result to being scaled to #sidebar height if set. If not, leaving #result at its original height.
My code:
window.onload = setDiv;
function setDiv() {
var e = document.getElementById('sidebar'); // Get the sidebar infos
var eh = e.offsetHeight // div height
if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page
alert(eh);
return true;
} else {
var eh = e.offsetHeight // div height
var d = document.getElementById('result') // Get the result div height
var dh = d.offsetHeight // div height
d.style.height = eh + 65 + 'px'; // Set result div height to sidebar height
alert(d);
document.write(dh);
return false;
}
}
I don't think HTML/CSS is needed.
Thank you.
This line seems wrong:
if ( typeof(eh) == "undefined" || "null") { // if sidebar isnt in the page
try this:
if ( typeof(eh) == "undefined" || typeof(eh) == null) { // if sidebar isnt in the page
Also, I would add in a try catch block. If there is a throw you won't even know your code did not execute.
This causes an error because e does not exist (yet):
var e = document.getElementById('sidebar'); // <<< This is what doesn't work
This is because your window.onload is not done right. Take the parentheses off:
window.onload = setDiv;
http://jsfiddle.net/userdude/u8DZx/3/
I want to demonstrate how easy this is to do in a library like jQuery. window.onload does not always work the way you think either; it's often better to use onDomReady, or $(document).ready() in jQuery. You can also add multiple handlers at different points in the page load, which is more difficult just using the window.onload method.
$(document).ready(function(){
setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
var $sidebar = $('#sidebar');
if ($sidebar.size() === 0) {
return true;
} else {
$('#result').animate({
height : $('#sidebar').height()
}, 5000);
return false;
}
}
http://jsfiddle.net/userdude/u8DZx/1/
If you don't want the effect, just do:
$('#result').height($('#sidebar').height());
And if you actually meant to use offsetHeight, which it doesn't sound like that's what you want (height instead), you could do this:
$(document).ready(function(){
setTimeout(function(){setDiv();},2000); // So you can see the transition
});
function setDiv() {
var $sidebar = $('#sidebar');
if ($sidebar.size() === 0) {
return true;
} else {
$('#result').offset($('#sidebar').offset());
return false;
}
}
http://jsfiddle.net/userdude/u8DZx/2/

How to detect browser support File API drag n drop

I like to add a background on a div only for browsers which support drag & drop for files
I don't like to use modernizr though, just a one line script
Why not just copy required parts from Modernizr?
var isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
// When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
var isSupported = eventName in element;
if ( !isSupported ) {
// If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = typeof element[eventName] == 'function';
// If property was created, "remove it" (by setting value to `undefined`)
if ( typeof element[eventName] != 'undefined' ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})();
Usage:
if (isEventSupported('dragstart') && isEventSupported('drop')) {
...
}
And for File API:
var isFileAPIEnabled = function() {
return !!window.FileReader;
};
You can use:
return 'draggable' in document.createElement('span') && typeof(window.FileReader) != 'undefined';
If you don't want to deal with Modernizr at all, you can just replicate what it does for drag'n'drop detection:
var supportsDragAndDrop = function() {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
}
Got it from Modernizr GitHub repository:
https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js
checkout modernizr source code technique for the HTML5 drag and drop detection https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js
except this seems to incorrectly detect iOS as supporting drag and drop
Not sure why everybody needs to create a new element to check this. I think it's enough to just check that the body element supports dragging events and that the browser supports the File API
supportsDragAndDrop(){
body = document.body
return ("draggable" in body || ("ondragstart" in body && "ondrop" in body))
&& window.FormData && window.FileReader
}

Categories