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
Related
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
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 am using file uploader from one of the plugin.
That php file called at file onchange event by ajax.
I got a file at php.
I can upload file manually by the help of this
$target_path = "../../../uploads/extension/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
But i want upload a file like other file uploading in Media. Its stored in uploads/2014/07 (i.e) upload/yearFolder/MonthFolder.
How to upload file like wise. I used wp_handle_upload(). but it returns undefined to call. So how to upload file.
Use the given steps
ajaxupload.3.5.js Code
/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.5 (23.06.2009)
*/
/**
* Changes from the previous version:
* 1. Added better JSON handling that allows to use 'application/javascript' as a response
* 2. Added demo for usage with jQuery UI dialog
* 3. Fixed IE "mixed content" issue when used with secure connections
*
* For the full changelog please visit:
* http://valums.com/ajax-upload-changelog/
*/
(function(){
var d = document, w = window;
/**
* Get element by id
*/
function get(element){
if (typeof element == "string")
element = d.getElementById(element);
return element;
}
/**
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}
/**
* Creates and returns element from html chunk
*/
var toElement = function(){
var div = d.createElement('div');
return function(html){
div.innerHTML = html;
var el = div.childNodes[0];
div.removeChild(el);
return el;
}
}();
function hasClass(ele,cls){
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement["getBoundingClientRect"]){
// Get Offset using getBoundingClientRect
// http://ejohn.org/blog/getboundingclientrect-is-awesome/
var getOffset = function(el){
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
// for ie
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
// while others are logical. Make all logical, like in IE8.
zoom = 1;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
if (zoom > 1){
clientTop = 0;
clientLeft = 0;
}
var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
return {
top: top,
left: left
};
}
} else {
// Get offset adding all offsets
var getOffset = function(el){
if (w.jQuery){
return jQuery(el).offset();
}
var top = 0, left = 0;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
}
while (el = el.offsetParent);
return {
left: left,
top: top
};
}
}
function getBox(el){
var left, right, top, bottom;
var offset = getOffset(el);
left = offset.left;
top = offset.top;
right = left + el.offsetWidth;
bottom = top + el.offsetHeight;
return {
left: left,
right: right,
top: top,
bottom: bottom
};
}
/**
* Crossbrowser mouse coordinates
*/
function getMouseCoords(e){
// pageX/Y is not supported in IE
// http://www.quirksmode.org/dom/w3c_cssom.html
if (!e.pageX && e.clientX){
// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
// while others are logical (offset).
var zoom = 1;
var body = document.body;
if (body.getBoundingClientRect) {
var bound = body.getBoundingClientRect();
zoom = (bound.right - bound.left)/body.clientWidth;
}
return {
x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
};
}
return {
x: e.pageX,
y: e.pageY
};
}
/**
* Function generates unique id
*/
var getUID = function(){
var id = 0;
return function(){
return 'ValumsAjaxUpload' + id++;
}
}();
function fileFromPath(file){
return file.replace(/.*(\/|\\)/, "");
}
function getExt(file){
return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}
// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
if (button.jquery){
// jquery object was passed
button = button[0];
} else if (typeof button == "string" && /^#.*/.test(button)){
button = button.slice(1);
}
button = get(button);
this._input = null;
this._button = button;
this._disabled = false;
this._submitting = false;
// Variable changes to true if the button was clicked
// 3 seconds ago (requred to fix Safari on Mac error)
this._justClicked = false;
this._parentDialog = d.body;
if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
var parentDialog = jQuery(this._button).parents('.ui-dialog');
if (parentDialog.length){
this._parentDialog = parentDialog[0];
}
}
this._settings = {
// Location of the server-side upload script
action: 'upload.php',
// File upload name
name: 'userfile',
// Additional data to send
data: {},
// Submit file as soon as it's selected
autoSubmit: true,
// The type of data that you're expecting back from the server.
// Html and xml are detected automatically.
// Only useful when you are using json data as a response.
// Set to "json" in that case.
responseType: false,
// When user selects a file, useful with autoSubmit disabled
onChange: function(file, extension){},
// Callback to fire before file is uploaded
// You can return false to cancel upload
onSubmit: function(file, extension){},
// Fired when file upload is completed
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
onComplete: function(file, response) {}
};
// Merge the users options with our defaults
for (var i in options) {
this._settings[i] = options[i];
}
this._createInput();
this._rerouteClicks();
}
// assigning methods to our class
AjaxUpload.prototype = {
setData : function(data){
this._settings.data = data;
},
disable : function(){
this._disabled = true;
},
enable : function(){
this._disabled = false;
},
// removes ajaxupload
destroy : function(){
if(this._input){
if(this._input.parentNode){
this._input.parentNode.removeChild(this._input);
}
this._input = null;
}
},
/**
* Creates invisible file input above the button
*/
_createInput : function(){
var self = this;
var input = d.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
input.setAttribute('id', this._settings.name);
var styles = {
'position' : 'absolute'
,'margin': '-5px 0 0 -175px'
,'padding': 0
,'top': '590px !important'
,'left': '560px !important'
,'width': '110px'
,'height': '30px'
,'fontSize': '14px'
,'opacity': 0
,'cursor': 'pointer'
,'display' : 'none'
,'zIndex' : 2147483583 //Max zIndex supported by Opera 9.0-9.2x
// Strange, I expected 2147483647
};
for (var i in styles){
input.style[i] = styles[i];
}
// Make sure that element opacity exists
// (IE uses filter instead)
if ( ! (input.style.opacity === "0")){
input.style.filter = "alpha(opacity=0)";
}
this._parentDialog.appendChild(input);
addEvent(input, 'change', function(){
// get filename from input
var file = fileFromPath(this.value);
if(self._settings.onChange.call(self, file, getExt(file)) == false ){
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit){
self.submit();
}
});
// Fixing problem with Safari
// The problem is that if you leave input before the file select dialog opens
// it does not upload the file.
// As dialog opens slowly (it is a sheet dialog which takes some time to open)
// there is some time while you can leave the button.
// So we should not change display to none immediately
addEvent(input, 'click', function(){
self.justClicked = true;
setTimeout(function(){
// we will wait 3 seconds for dialog to open
self.justClicked = false;
}, 3000);
});
this._input = input;
},
_rerouteClicks : function (){
var self = this;
// IE displays 'access denied' error when using this method
// other browsers just ignore click()
// addEvent(this._button, 'click', function(e){
// self._input.click();
// });
var box, dialogOffset = {top:0, left:0}, over = false;
addEvent(self._button, 'mouseover', function(e){
if (!self._input || over) return;
over = true;
box = getBox(self._button);
if (self._parentDialog != d.body){
dialogOffset = getOffset(self._parentDialog);
}
});
// we can't use mouseout on the button,
// because invisible input is over it
addEvent(document, 'mousemove', function(e){
var input = self._input;
if (!input || !over) return;
if (self._disabled){
removeClass(self._button, 'hover');
input.style.display = 'none';
return;
}
var c = getMouseCoords(e);
if ((c.x >= box.left) && (c.x <= box.right) &&
(c.y >= box.top) && (c.y <= box.bottom)){
input.style.top = c.y - dialogOffset.top + 'px';
input.style.left = c.x - dialogOffset.left + 'px';
input.style.display = 'block';
addClass(self._button, 'hover');
} else {
// mouse left the button
over = false;
if (!self.justClicked){
input.style.display = 'none';
}
removeClass(self._button, 'hover');
}
});
},
/**
* Creates iframe with unique name
*/
_createIframe : function(){
// unique name
// We cannot use getTime, because it sometimes return
// same value in safari :(
var id = getUID();
// Remove ie6 "This page contains both secure and nonsecure items" prompt
// http://tinyurl.com/77w9wh
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
iframe.id = id;
iframe.style.display = 'none';
d.body.appendChild(iframe);
return iframe;
},
/**
* Upload file without refreshing the page
*/
submit : function(){
var self = this, settings = this._settings;
if (this._input.value === ''){
// there is no file
return;
}
// get filename from input
var file = fileFromPath(this._input.value);
// execute user event
if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
// Create new iframe for this submission
var iframe = this._createIframe();
// Do not submit if user function returns false
var form = this._createForm(iframe);
form.appendChild(this._input);
form.submit();
d.body.removeChild(form);
form = null;
this._input = null;
// create new input
this._createInput();
var toDeleteFlag = false;
addEvent(iframe, 'load', function(e){
if (// For Safari
iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
// For FF, IE
iframe.src == "javascript:'<html></html>';"){
// First time around, do not delete.
if( toDeleteFlag ){
// Fix busy state in FF3
setTimeout( function() {
d.body.removeChild(iframe);
}, 0);
}
return;
}
var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
// fixing Opera 9.26
if (doc.readyState && doc.readyState != 'complete'){
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false"){
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
var response;
if (doc.XMLDocument){
// response is a xml document IE property
response = doc.XMLDocument;
} else if (doc.body){
// response is html document or plain text
response = doc.body.innerHTML;
if (settings.responseType && settings.responseType.toLowerCase() == 'json'){
// If the document was sent as 'application/javascript' or
// 'text/javascript', then the browser wraps the text in a <pre>
// tag and performs html encoding on the contents. In this case,
// we need to pull the original text content from the text node's
// nodeValue property to retrieve the unmangled content.
// Note that IE6 only understands text/html
if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE'){
response = doc.body.firstChild.firstChild.nodeValue;
}
if (response) {
response = window["eval"]("(" + response + ")");
} else {
response = {};
}
}
} else {
// response is a xml document
var response = doc;
}
settings.onComplete.call(self, file, response);
// Reload blank page, so that reloading main page
// does not re-submit the post. Also, remember to
// delete the frame
toDeleteFlag = true;
// Fix IE mixed content issue
iframe.src = "javascript:'<html></html>';";
});
} else {
// clear input to allow user to select same file
// Doesn't work in IE6
// this._input.value = '';
d.body.removeChild(this._input);
this._input = null;
// create new input
this._createInput();
}
},
/**
* Creates form, that will be submitted to iframe
*/
_createForm : function(iframe){
var settings = this._settings;
// method, enctype must be specified here
// because changing this attr on the fly is not allowed in IE 6/7
var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
form.style.display = 'none';
form.action = settings.action;
form.target = iframe.name;
d.body.appendChild(form);
// Create hidden input element for each data key
for (var prop in settings.data){
var el = d.createElement("input");
el.type = 'hidden';
el.name = prop;
el.value = settings.data[prop];
form.appendChild(el);
}
return form;
}
};
})();
add this file in your header(like:<script type="text/javascript" src="<?php print get_stylesheet_directory_uri() ;?>/js/ajaxupload.3.5.js" ></script> )
Now place this code below it in header
<script type="text/javascript" >
jQuery(function(){
var btnUpload=jQuery('#upload');
var status=jQuery('#status');
new AjaxUpload(btnUpload, {
action: '<?php echo get_template_directory_uri();?>/upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
//status.text('Uploading...');
status.html('<img style="float:right;position:absolute;right:-30px;top:10px" width="16" border="0" height="16" alt="" src="<?php echo get_template_directory_uri(); ?>/img/ajax-loader.gif" id="pleasewait">');
},
onComplete: function(file, response){
//alert(response);
//On completion clear the status
status.text('');
//Add uploaded file to list
if(response!='error'){
//jQuery('<li></li>').appendTo('#files').html('<img src="'+response+'" alt="" /><br />'+file).addClass('success');
jQuery('<li></li>').appendTo('#files').html(file).addClass('success');
jQuery('<input type="hidden" id="uploaded-pres" value="'+response+'"/>').appendTo('#files');
} else{
jQuery('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
});
</script>
Now make a upload-file.php in root folder
<?php
include_once('../../../wp-load.php');
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['uploadfile'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
//echo "File is successfully uploaded.\n";
echo $movefile['url'];
} else {
echo "error";
}
?>
And lastly in html where you want to use upload button just put this
<div id="upload" ><span>Upload File<span></div><span id="status" ></span>
<ul id="files" ></ul>
Note: Its looking lengthy because i have written the js file code and php code at one place.
So arrange these file.
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);
I want to add a java-script to click a button when bottom of page is reached...the code for that is
<script>
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
}
//taken from http://james.padolsey.com/javascript/get-document-height-cross-browser/
function getDocHeight() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
document.addEventListener("scroll", function (event) {
if (getDocHeight() == getScrollXY()[1] + window.innerHeight) {
document.getElementById('next').click()
}
});
</script>
the problem is that the button is SQLFORM's submit button, so my question is what is the id of SQLFORM submit button, or how can i define it..i have tried the following but with no success.
form2.custom.widget.submit_button['_id']='next'
it shows the error 'NoneType' object does not support item assignment.
there is a some excellent information on Custom CSS classes for SQLFORM widget input in web2py, but i still cant figure this out....
You can identify the submit button with a jQuery selector, such as "input[type=submit]" (or more specifically, "#submit_record__row input[type=submit]"). If you want to assign an ID, you can do:
form2.custom.submit['_id'] = 'next'
or:
form2.element('input[type=submit]')['_id'] = 'next'