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
Related
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.
I have a side menu and when it's open, the body can be partially seen. My side menu might be long so you could scroll on it. But when the menu is at the bottom you then scroll on the body, and I don't want this behaviour.
Similar to Scrolling only content div, others should be fixed but I'm using React. Other content should be scrollable when my side menu is closed. Think of the content as side menu in the example in the link. So far I'm using the same technique provided by that answer but it's ugly (kinda jQuery):
preventOverflow = (menuOpen) => { // this is called when side menu is toggled
const body = document.getElementsByTagName('body')[0]; // this should be fixed when side menu is open
if (menuOpen) {
body.className += ' overflow-hidden';
} else {
body.className = body.className.replace(' overflow-hidden', '');
}
}
// css
.overflow-hidden {
overflow-y: hidden;
}
What should I do with Reactjs?
You should make a meta component in react to change things on the body as well as changing things like document title and things like that. I made one a while ago to do that for me. I'll add it here.
Usage
render() {
return (
<div>
<DocumentMeta bodyClasses={[isMenuOpen ? 'no-scroll' : '']} />
... rest of your normal code
</div>
)
}
DocumentMeta.jsx
import React from 'react';
import _ from 'lodash';
import withSideEffect from 'react-side-effect';
var HEADER_ATTRIBUTE = "data-react-header";
var TAG_NAMES = {
META: "meta",
LINK: "link",
};
var TAG_PROPERTIES = {
NAME: "name",
CHARSET: "charset",
HTTPEQUIV: "http-equiv",
REL: "rel",
HREF: "href",
PROPERTY: "property",
CONTENT: "content"
};
var getInnermostProperty = (propsList, property) => {
return _.result(_.find(propsList.reverse(), property), property);
};
var getTitleFromPropsList = (propsList) => {
var innermostTitle = getInnermostProperty(propsList, "title");
var innermostTemplate = getInnermostProperty(propsList, "titleTemplate");
if (innermostTemplate && innermostTitle) {
return innermostTemplate.replace(/\%s/g, innermostTitle);
}
return innermostTitle || "";
};
var getBodyIdFromPropsList = (propsList) => {
var bodyId = getInnermostProperty(propsList, "bodyId");
return bodyId;
};
var getBodyClassesFromPropsList = (propsList) => {
return propsList
.filter(props => props.bodyClasses && Array.isArray(props.bodyClasses))
.map(props => props.bodyClasses)
.reduce((classes, list) => classes.concat(list), []);
};
var getTagsFromPropsList = (tagName, uniqueTagIds, propsList) => {
// Calculate list of tags, giving priority innermost component (end of the propslist)
var approvedSeenTags = {};
var validTags = _.keys(TAG_PROPERTIES).map(key => TAG_PROPERTIES[key]);
var tagList = propsList
.filter(props => props[tagName] !== undefined)
.map(props => props[tagName])
.reverse()
.reduce((approvedTags, instanceTags) => {
var instanceSeenTags = {};
instanceTags.filter(tag => {
for(var attributeKey in tag) {
var value = tag[attributeKey].toLowerCase();
var attributeKey = attributeKey.toLowerCase();
if (validTags.indexOf(attributeKey) == -1) {
return false;
}
if (!approvedSeenTags[attributeKey]) {
approvedSeenTags[attributeKey] = [];
}
if (!instanceSeenTags[attributeKey]) {
instanceSeenTags[attributeKey] = [];
}
if (!_.has(approvedSeenTags[attributeKey], value)) {
instanceSeenTags[attributeKey].push(value);
return true;
}
return false;
}
})
.reverse()
.forEach(tag => approvedTags.push(tag));
// Update seen tags with tags from this instance
_.keys(instanceSeenTags).forEach((attr) => {
approvedSeenTags[attr] = _.union(approvedSeenTags[attr], instanceSeenTags[attr])
});
instanceSeenTags = {};
return approvedTags;
}, []);
return tagList;
};
var updateTitle = title => {
document.title = title || document.title;
};
var updateBodyId = (id) => {
document.body.setAttribute("id", id);
};
var updateBodyClasses = classes => {
document.body.className = "";
classes.forEach(cl => {
if(!cl || cl == "") return;
document.body.classList.add(cl);
});
};
var updateTags = (type, tags) => {
var headElement = document.head || document.querySelector("head");
var existingTags = headElement.querySelectorAll(`${type}[${HEADER_ATTRIBUTE}]`);
existingTags = Array.prototype.slice.call(existingTags);
// Remove any duplicate tags
existingTags.forEach(tag => tag.parentNode.removeChild(tag));
if (tags && tags.length) {
tags.forEach(tag => {
var newElement = document.createElement(type);
for (var attribute in tag) {
if (tag.hasOwnProperty(attribute)) {
newElement.setAttribute(attribute, tag[attribute]);
}
}
newElement.setAttribute(HEADER_ATTRIBUTE, "true");
headElement.insertBefore(newElement, headElement.firstChild);
});
}
};
var generateTagsAsString = (type, tags) => {
var html = tags.map(tag => {
var attributeHtml = Object.keys(tag)
.map((attribute) => {
const encodedValue = HTMLEntities.encode(tag[attribute], {
useNamedReferences: true
});
return `${attribute}="${encodedValue}"`;
})
.join(" ");
return `<${type} ${attributeHtml} ${HEADER_ATTRIBUTE}="true" />`;
});
return html.join("\n");
};
var reducePropsToState = (propsList) => ({
title: getTitleFromPropsList(propsList),
metaTags: getTagsFromPropsList(TAG_NAMES.META, [TAG_PROPERTIES.NAME, TAG_PROPERTIES.CHARSET, TAG_PROPERTIES.HTTPEQUIV, TAG_PROPERTIES.CONTENT], propsList),
linkTags: getTagsFromPropsList(TAG_NAMES.LINK, [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF], propsList),
bodyId: getBodyIdFromPropsList(propsList),
bodyClasses: getBodyClassesFromPropsList(propsList),
});
var handleClientStateChange = ({title, metaTags, linkTags, bodyId, bodyClasses}) => {
updateTitle(title);
updateTags(TAG_NAMES.LINK, linkTags);
updateTags(TAG_NAMES.META, metaTags);
updateBodyId(bodyId);
updateBodyClasses(bodyClasses)
};
var mapStateOnServer = ({title, metaTags, linkTags}) => ({
title: HTMLEntities.encode(title),
meta: generateTagsAsString(TAG_NAMES.META, metaTags),
link: generateTagsAsString(TAG_NAMES.LINK, linkTags)
});
var DocumentMeta = React.createClass({
propTypes: {
title: React.PropTypes.string,
titleTemplate: React.PropTypes.string,
meta: React.PropTypes.arrayOf(React.PropTypes.object),
link: React.PropTypes.arrayOf(React.PropTypes.object),
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array
]),
bodyClasses: React.PropTypes.array,
},
render() {
if (Object.is(React.Children.count(this.props.children), 1)) {
return React.Children.only(this.props.children);
} else if (React.Children.count(this.props.children) > 1) {
return (
<span>
{this.props.children}
</span>
);
}
return null;
},
});
DocumentMeta = withSideEffect(reducePropsToState, handleClientStateChange, mapStateOnServer)(DocumentMeta);
module.exports = DocumentMeta;
This component could probably be changed a little for your case (withSideEffect is used for both client and server side rendering... if you arent using server side rendering then its probably not completely necessary) but the component will work on client side rendering if you would like to use it there as well.
ReactJS doesn't have direct access to the <body> element, and that's the element that needs to have its overflow-y style changed. So while what you're doing isn't perhaps the prettiest code, it's not entirely wrong either.
The only real suggestion I'd give is (shudder) using inline styles on the body instead of a classname so as to avoid having to introduce the CSS declaration. As long as your menu is the only thing responsible for updating the overflow-y attribute, there's no reason you can't use an inline style on it. Mashing that down with the ?: operator results in fairly simple code:
body.style.overflowY = menuOpen ? "hidden" : "";
And then you can just delete the .overflow-hidden class in its entirety.
If for some reason multiple things are managing the overflow state of the body, you might want to stick with classnames and assign a unique one for each thing managing it, something like this:
if (menuOpen) {
body.className += ' menu-open';
}
else {
// Use some tricks from jQuery to remove the "menu-open" class more elegantly.
var className = " " + body.className + " ";
className = className.replace(" overflow-hidden ", " ").replace(/\s+/, " ");
className = className.substr(1, className.length - 2);
}
CSS:
body.menu-open {
overflow-y: hidden;
}
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
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.
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);