How can I test for clip-path support? - css

clip-path:shape() does not seem to work in IE (no surprise) and Firefox (a bit surprised). Is there a way to test for clip-path support? I use modernizr. (By the way, I know I can get this to work using SVGs and -webkit-clip-path:url(#mySVG))

You asked this a while ago, and to be honest, I'm not sure if Modernizr has yet to add support for this, but it's pretty easy to roll your own test in this case.
The steps are:
Create, but do not append, a DOM element.
Check that it supports any kind of clipPath by checking the JS style attribute of the newly created element (element.style.clipPath === '' if it can support it).
Check that it supports CSS clip path shapes by making element.style.clipPath equal some valid CSS clip path shape.
Of course, it's a little more complex than that, as you have to check for vendor-specific prefixes.
Here it is all together:
var areClipPathShapesSupported = function () {
var base = 'clipPath',
prefixes = [ 'webkit', 'moz', 'ms', 'o' ],
properties = [ base ],
testElement = document.createElement( 'testelement' ),
attribute = 'polygon(50% 0%, 0% 100%, 100% 100%)';
// Push the prefixed properties into the array of properties.
for ( var i = 0, l = prefixes.length; i < l; i++ ) {
var prefixedProperty = prefixes[i] + base.charAt( 0 ).toUpperCase() + base.slice( 1 ); // remember to capitalize!
properties.push( prefixedProperty );
}
// Interate over the properties and see if they pass two tests.
for ( var i = 0, l = properties.length; i < l; i++ ) {
var property = properties[i];
// First, they need to even support clip-path (IE <= 11 does not)...
if ( testElement.style[property] === '' ) {
// Second, we need to see what happens when we try to create a CSS shape...
testElement.style[property] = attribute;
if ( testElement.style[property] !== '' ) {
return true;
}
}
}
return false;
};
Here's a codepen proof-of-concept: http://codepen.io/anon/pen/YXyyMJ

You can test with Modernizr.
(function (Modernizr) {
// Here are all the values we will test. If you want to use just one or two, comment out the lines of test you don't need.
var tests = [{
name: 'svg',
value: 'url(#test)'
}, // False positive in IE, supports SVG clip-path, but not on HTML element
{
name: 'inset',
value: 'inset(10px 20px 30px 40px)'
}, {
name: 'circle',
value: 'circle(60px at center)'
}, {
name: 'ellipse',
value: 'ellipse(50% 50% at 50% 50%)'
}, {
name: 'polygon',
value: 'polygon(50% 0%, 0% 100%, 100% 100%)'
}
];
var t = 0, name, value, prop;
for (; t < tests.length; t++) {
name = tests[t].name;
value = tests[t].value;
Modernizr.addTest('cssclippath' + name, function () {
// Try using window.CSS.supports
if ('CSS' in window && 'supports' in window.CSS) {
for (var i = 0; i < Modernizr._prefixes.length; i++) {
prop = Modernizr._prefixes[i] + 'clip-path'
if (window.CSS.supports(prop, value)) {
return true;
}
}
return false;
}
// Otherwise, use Modernizr.testStyles and examine the property manually
return Modernizr.testStyles('#modernizr { ' + Modernizr._prefixes.join('clip-path:' + value + '; ') + ' }', function (elem, rule) {
var style = getComputedStyle(elem),
clip = style.clipPath;
if (!clip || clip == "none") {
clip = false;
for (var i = 0; i < Modernizr._domPrefixes.length; i++) {
test = Modernizr._domPrefixes[i] + 'ClipPath';
if (style[test] && style[test] !== "none") {
clip = true;
break;
}
}
}
return Modernizr.testProp('clipPath') && clip;
});
});
}
})(Modernizr);
Check this codepen to see it in action.

Related

Rendering components only if they can fit inside a flex container

I am trying to build a toolbar that hides components from the right if there is not enough space to render them. My approach is to use refs and add up the width and render based on the condition if the total width has been overflowed. I want to get something working and go on improving it from there. It seems to work 'ok' when the screen size is decreased but not when trying to 're-render' the components when there is room. I suspect adding a display style of 'none' is causing some of the issues.
componentDidMount() {
this.littleFunction();
window.addEventListener('resize', this.littleFunction);
}
littleFunction = () => {
let sofar = 0;
for (const ref in this.refs) {
sofar += this.refs[ref].offsetWidth;
const index = ref.indexOf('test');
console.log(ref, sofar, this.input.offsetWidth);
if (sofar > this.input.offsetWidth && index === -1) {
this.refs[ref].style.display = 'none';
}
// // console.log(typeof this.refs[ref].style.display, this.refs[ref].style.display);
// if (this.refs[ref] !== this.input) {
// sofar = this.refs[ref].offsetWidth + sofar;
// }
// const index = ref.indexOf('test');
// // console.log(sofar, this.input.offsetWidth, index);
// if (sofar >= this.input.offsetWidth && index === -1) {
// this.refs[ref].style.display = 'none';
//
// this.forceUpdate();
// } else if (sofar < this.input.offsetWidth && index === -1) {
// // console.log('inhiaaa', sofar, this.input.offsetWidth);
// this.refs[ref].style.display = '';
//
// this.forceUpdate();
// }
}
}
After thinking about this for a while, i realized that if i set the style to display: 'none', the next time I try to run this logic to check how many components can fit, I am actually not getting the length back from the components that were previously set to display: 'none'. What I did was save the width of the components before applying calling the function.
componentDidMount() {
this.widths = new List();
for (const ref in this.refs) {
this.widths = this.widths.push(Map({
name: ref,
length: this.refs[ref].offsetWidth,
}));
}
this.littleFunction();
window.addEventListener('resize', this.littleFunction);
}
littleFunction = () => {
let sofar = 0;
this.widths.forEach(item => {
sofar += item.get('length');
const index = item.get('name').indexOf('test');
if (sofar > this.input.offsetWidth && index === -1) {
this.refs[item.get('name')].style.display = 'none';
// this.forceUpdate();
} else if (index === -1) {
this.refs[item.get('name')].style.display = 'inline';
// this.forceUpdate();
}
});
}
Have the toolbar to have style { width: '100%', overflow: 'hidden', whiteSpace: 'nowrap' } should give you the desired effect.

min-height : 100vh not working in ie8

In IE8 when i give min-height in vh then ie8 ignore it and not work.in other brower work well.some where i read that vh not support ie8 any solution that i use vh in ie8.
<div class=" item Finish " id="Finish" style="overflow: visible!important;" >
<div style="background-color: #27AE61!important;padding: 0px !important;min-height:85vh;overflow: visible!important;">
<-- html code -->
</div>
</div>
Silver Ringvee's answer is absolutely correct, except that default jQuery .css() functionality is broken when you want to do stuff like .css('margin-right') to get the right margin of an element. I found this issue when using fancyBox. I fixed that by checking if props is a string, if so parseProps($.extend({}, props)) is not used. I also added a check if multiple arguments were given, to support css('margin-right', '12px'). Here's my code:
(function ($, window) {
var $win = $(window), _css = $.fn.css;
function viewportToPixel(val) {
var vwh_match = val.match(/[vwh]+/);
var digits_match = val.match(/\d+/);
if (vwh_match && vwh_match.length && digits_match && digits_match.length) {
return (vwh_match[0] == 'vh' ? $win.height() : $win.width()) * (digits_match[0] / 100) + 'px';
}
return val;
}
function parseProps(props) {
var p, prop;
for (p in props) {
prop = props[p];
if (/[vwh]$/.test(prop)) {
props[p] = viewportToPixel(prop);
}
}
return props;
}
$.fn.css = function (props) {
var self = this,
originalArguments = arguments,
update = function () {
if (typeof props === 'string' || props instanceof String) {
if (originalArguments.length > 1) {
var argumentsObject = {};
argumentsObject[originalArguments[0]] = originalArguments[1];
return _css.call(self, parseProps($.extend({}, argumentsObject)));
} else {
return _css.call(self, props);
}
} else {
return _css.call(self, parseProps($.extend({}, props)));
}
};
$win.resize(update);
return update();
};
}(jQuery, window));
vw and vh units are supported by IE 9 and up.
Try this:
(function( $, window ){
var $win = $(window)
, _css = $.fn.css;
function viewportToPixel( val ) {
var percent = val.match(/\d+/)[0] / 100,
unit = val.match(/[vwh]+/)[0];
return (unit == 'vh' ? $win.height() : $win.width()) * percent + 'px';
}
function parseProps( props ) {
var p, prop;
for ( p in props ) {
prop = props[ p ];
if ( /[vwh]$/.test( prop ) ) {
props[ p ] = viewportToPixel( prop );
}
}
return props;
}
$.fn.css = function( props ) {
var self = this,
update = function() {
return _css.call( self, parseProps( $.extend( {}, props ) ) );
};
$win.resize( update );
return update();
};
}( jQuery, window ));
$('div').css({
height: '50vh',
width: '50vw',
marginTop: '25vh',
marginLeft: '25vw',
fontSize: '10vw'
});
Working demo: http://jsbin.com/izosuy/1/edit?js,output
Works well in IE8 as well!
Read this topic for more info: Is there any cross-browser javascript for making vh and vw units work

matchmedia polyfill implement

How and Why does the polyfill can work?
w.matchMedia = w.matchMedia || (function( doc, undefined ) {
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( w.document ));
paulirish alse implement it in another similar way, https://github.com/paulirish/matchMedia.js/blob/master/matchMedia.js
the key code is as following
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';
}
};
Both work the same way.
They just inject the media that you pass as a parameter, and use it to aply a predefined style (a width of 42 px for the first, and of 1px for the second),
If the width of the element is really the predefined one, the media is working and the function evaluates to true

Make fixed positioned div relatively to another div,

I started the first question here: but it was very hard to make the effect for each single page I had, So I thought if I made the div that I wanted to make fixed not fixed to the screen scroll
Very Hard to compute heights with pure math and it doesn't work ultimately as you need to modify the calculation for every single page
Here is the code :
<script >window.addEventListener("scroll",function() {
if(window.scrollY >= 148) {
document.getElementById('main_nav').style.position = 'absolute';
document.getElementById('main_nav').style.bottom = '65%';
}
if(window.scrollY <= 148){
document.getElementById('main_nav').style.position = 'fixed';
document.getElementById('main_nav').style.top = '42%';
}
});</script>
so to get things clear That piece of code depends on scroll height of screen.
I need to apply the following effect :
when the page loads the main_nav div is position:fixed.
On scrolling down
when main_nav is above some div by: say 20px it should stop position:fixed.
It should stand still at it's last place.
On scrolling up again.
It should restore the position fixed again .
"This creates the float effect till some point"
Someone I know gave me the link for this question and a js code and told me to past it here
so here its if it is not relevant to the subject please let me knw
Someone I know gave me the link for this question and a js code and told me to past it here
so here its if it is not relevant to the subject please let me know and I will delete it
/* ===========================================================
* fixate.js v1
* Use:
* Inspired by the original jquery sticky scroller
* ========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* FIXATE PUBLIC CLASS DEFINITION
* =============================== */
var Fixate = function (element, options) {
this.init(element, options);
}
Fixate.prototype = {
constructor: Fixate
, init: function (element, options) {
var self, opts;
this.$element = $(element);
opts = this.options = this.getOptions(options);
this.zindex = this.$element.css('z-index');
this.$window = $(window);
this.$doc = $(document);
this.$bottomCap = opts.bottomCapEl ? $(opts.bottomCapEl) : false;
this.$topCap = opts.topCapEl ? $(opts.topCapEl) : false;
this.bottomOffset = opts.windowInset.bottom || 0;
this.topOffset = opts.windowInset.top || 0;
this.top = this.$element.offset().top - parseFloat(this.$element.css('margin-top').replace(/auto/, 0)) - this.topOffset;
this.eto = this.$element.offset().top;
this.origTop = this.$element.css('top');
this.origBottom = this.$element.css('bottom');
this.z = (this.zindex === '0' || this.zindex === 'auto') ? opts.zindex : this.zindex;
this.bh = (this.$bottomCap) ? this.$bottomCap.outerHeight(true) : 0;
self = this;
this.$window.on('scroll', function (e) {
self.fixate();
});
this.$doc.on('DOMNodeInserted DOMNodeRemoved', function(e){
//Called when elements are added or removed from DOM
self.fixate();
});
}
, getOptions: function (options) {
options = $.extend({}, $.fn['fixate'].defaults, options, this.$element.data());
return options;
}
, fixate: function(){
var s = this.$window.scrollTop()
, h = this.$element.outerHeight(true);
// Calc offset onscroll to get most updated results - incasse ajaxed els come in
this.bco = (this.$bottomCap) ? this.$bottomCap.offset().top : 0;
this.tco = (this.$topCap) ? this.$topCap.offset().top + this.$topCap.outerHeight(true) : 0;
this.dh = this.$doc.height();
if(this.options.windowEdge === 'top'){
this.fixToTop(s, h);
} else {
this.fixToBottom(s, h);
}
}
, fixToTop: function (s, h) {
var bco = this.bco
, to = this.topOffset
, eto = this.eto
, bo = this.bottomOffset
, point = bco - h - bo - to;
if (s >= this.top) {
this.$element.css({
'position': 'fixed',
'top': to,
'z-index': this.z
});
this.fixTouchDevice();
// Bottom cap calc -check cpu factor
if (s >= point) {
this.$element.css({
'top': Math.round(point - this.top + parseFloat(this.origTop)),
'position': 'absolute'
});
}
} else {
this.$element.css({
'position': '',
'top': this.origTop,
'z-index': this.zindex
});
}
}
, fixToBottom: function (s, h) {
var bco = this.bco
, to = this.topOffset
, eto = this.eto
, bo = this.bottomOffset;
if (s >= ( bco - h - bo - to - this.top) ) {
this.$element.css({
'bottom': Math.round(this.dh-(bco - bo)),
'position': 'absolute'
});
this.fixTouchDevice();
} else {
this.$element.css({
'position': 'fixed',
'bottom': bo,
'z-index': this.z
});
}
}
, fixTouchDevice: function(){
//stick the footer at the bottom of the page if we're on an iPad/iPhone due to viewport/page bugs in mobile webkit
if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
this.$element.css("position", "static");
}
}
}
/* FIXATE PLUGIN DEFINITION
* ========================= */
$.fn.fixate = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('fixate'),
options = typeof option == 'object' && option;
if (!data) $this.data('fixate', (data = new Fixate(this, options)));
if (typeof option == 'string') data[option]();
})
}
$.fn.fixate.Constructor = Fixate;
$.fn.fixate.defaults = {
windowInset: {
top: 0,
bottom: 0
}
, windowEdge: 'top'
, bottomCapEl: 'footer'
, topCapEl: 'header'
, zindex: 5
};
}(window.jQuery);

Phantomjs doesn't render footers with a custom styles

I have the following example:
var page = require('webpage').create(),
system = require('system');
if (system.args.length < 3) {
console.log('Usage: printheaderfooter.js URL filename');
phantom.exit(1);
} else {
var address = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4',
margin: "1cm"
footer: {
height: "1cm",
contents: phantom.callback(function(pageNum, numPages) {
if (pageNum == numPages) {
return "";
}
return "<h1 class='footer_style'>Footer" + pageNum + " / " + numPages + "</h1>";
})
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}
In the example above I use footer_style class that look likes in my css file the following:
.footer_style {
text-align:right;
}
But unfortunately that dosen't works. I'm trying to create pdf file such as follows:
./phantomjs rasterize.js index.html test.pdf
We know that classes do not work but inline styles do. What we can do is replace the class with the computed style.
Here is a function that will take a piece of html, create a temporary element in the body with the html, compute the style for each element with a class, add the computed style inline and return the new html.
function replaceClassWithStyle(html) {
return page.evaluate(function(html) {
var host = document.createElement('div');
host.innerHTML = html;
document.body.appendChild(host); // if not appended, values will be blank
var elements = host.getElementsByTagName('*');
for (var i in elements) {
if (elements[i].className) {
elements[i].setAttribute('style', window.getComputedStyle(elements[i], null).cssText);
}
}
document.body.removeChild(host);
return host.innerHTML;
}, html);
}
Then simply call this function in your footer:
page.paperSize = {
footer: {
contents: phantom.callback(function(pageNum, numPages) {
if (pageNum == numPages) {
return "";
}
return replaceClassWithStyle("<h1 class='footer_style'>Footer" + pageNum + " / " + numPages + "</h1>");
})
}
};
You will need to move all this inside page.open().
I tested it and the footer is aligned to the right.
I have an update to mak's excellent answer for PhantomJS 1.9.7.
This version fixes:
Circumvent bug which 'blank's the parent document (PhantomJS 1.9.7)
Style mixups when styles are nested (do depth-first traversal instead)
Also works when tags do not have classes
/**
* Place HTML in the parent document, convert CSS styles to fixed computed style declarations, and return HTML.
* (required for headers/footers, which exist outside of the HTML document, and have trouble getting styling otherwise)
*/
function replaceCssWithComputedStyle(html) {
return page.evaluate(function(html) {
var host = document.createElement('div');
host.setAttribute('style', 'display:none;'); // Silly hack, or PhantomJS will 'blank' the main document for some reason
host.innerHTML = html;
// Append to get styling of parent page
document.body.appendChild(host);
var elements = host.getElementsByTagName('*');
// Iterate in reverse order (depth first) so that styles do not impact eachother
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].setAttribute('style', window.getComputedStyle(elements[i], null).cssText);
}
// Remove from parent page again, so we're clean
document.body.removeChild(host);
return host.innerHTML;
}, html);
}
From my past experience, phantomjs does not support styles in custom header/footer.
The only solution that I found is to apply an inline style like this :
var page = require('webpage').create(),
system = require('system');
if (system.args.length < 3) {
console.log('Usage: printheaderfooter.js URL filename');
phantom.exit(1);
} else {
var address = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4',
margin: "1cm",
footer: {
height: "1cm",
contents: phantom.callback(function(pageNum, numPages) {
return "<h1 style='text-align:right'>Footer" + pageNum + " / " + numPages + "</h1>";
})
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}
Note : A comma is missing in your code after margin: "1cm"

Resources