I am trying to update my javascript to be jquery.
Here is the javascript (this is working correctly)
<script type="text/javascript">
function getWindowHeight() {
var windowHeight = 0;
if (typeof (window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
}
function setContent() {
if (document.getElementById) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = document.getElementById('content')
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
contentElement.style.visibility = 'visible';
}
else {
contentElement.style.position = 'static';
contentElement.style.visibility = 'visible';
}
}
}
}
window.onload = function () {
setContent();
}
window.onresize = function () {
setContent();
}
</script>
Here is the jquery (this just returns a blank screen without errors)
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getWindowHeight() {
var windowHeight = 0;
if (typeof (window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if ($.documentElement && $.documentElement.clientHeight) {
windowHeight = $.documentElement.clientHeight;
}
else {
if ($.body && $.body.clientHeight) {
windowHeight = $.body.clientHeight;
}
}
}
return windowHeight;
}
function setContent() {
if ($) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = $('content')
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
contentElement.style.visibility = 'visible';
}
else {
contentElement.style.position = 'static';
contentElement.style.visibility = 'visible';
}
}
}
}
$(document).ready= function () {
setContent();
}
$(document).onresize = function () {
setContent();
}
</script>
Your function bindings at the end are a bit off, they should look like this:
$(setContent);
$(window).resize(setContent);
This will lead to other errors though, $ isn't a replacement for document, overall I think this is what you're looking for:
function setContent() {
var windowHeight = $(window).height();
if (windowHeight > 0) {
var contentHeight = $('#content').height();
if (windowHeight - contentHeight > 0) {
$('#content').css({ position: 'relative',
top: ((windowHeight / 2) - (contentHeight / 2)) + 'px',
visibility: 'visible' });
}
else {
$('#content').css({ position: 'static',
visibility: 'visible' });
}
}
}
$(setContent);
$(window).resize(setContent);​
You can give it a try here, a few notes on this compared to the code in the question:
document.getElementById('content') is $('#content'), notice the # for an #ID selector.
$(window).height() uses .height() to take care of the cross browser/various case heights.
You can't replace document with $, they're very different things :)
.css() takes an object, so you can shorten you style setting above.
try this code..
$(function(){
var windowHeight = $(window).height();
var content = $('content');
if (windowHeight > 0) {
if (windowHeight - content.height() > 0) {
content.css({'position':'relative','top':((windowHeight/2) - (content.height()/2) + 'px','visibility':'visible' });
}else{
content.css({'position':'static','visibility':'visible'});
}
}
});
Related
I have a code which is supposed to trigger various functions as I scroll down (each function draws a chart below another). The thing is that this code works well on my screen but when I run it on a bigger screen the functions are not triggered.
I haven't harcoded anything, I have debugged, and tested each conditions and all throw true.
This is the troublesome snippet:
$(window).scroll(function() {
if ($('#chartdiv').html().length != 0) {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if (Math.round((scrollHeight - scrollPosition) / scrollHeight) === 0) {
if ($('#chartdiv2').html().length == 0) {
drawChar2();
}
okas.
else if ($('#chartdiv3').html().length == 0) {
drawChar3();
} else if ($('#chartdiv4').html().length == 0) {
drawChar4();
} else if ($('#chartdiv5').html().length == 0) {
drawChar5();
}
}
}
});
If your screen is very big, you have to add if condition.
Because there is no reason to scroll.
$(window).scroll(function() {
if ($('#chartdiv').html().length != 0) {
var $window = $(window);
var windowHeight = $window.height();
var scrollHeight = $(document).height();
var scrollPosition = windowHeight + $window.scrollTop();
if (windowHeight === scrollHeight || // add this condition!!!
Math.round((scrollHeight - scrollPosition) / scrollHeight) === 0) {
if ($('#chartdiv2').html().length == 0) {
drawChar2();
} else if ($('#chartdiv3').html().length == 0) {
drawChar3();
} else if ($('#chartdiv4').html().length == 0) {
drawChar4();
} else if ($('#chartdiv5').html().length == 0) {
drawChar5();
}
}
}
});
I am trying to get the visibility of the element from viewport in percentage (number %).
Below is the code which I tired, but something is missing.
function calculateVisibilityForDiv(div$) {
var windowHeight = window.innerWidth ||
document.documentElement.clientWidth,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll +
windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll +
windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = { top: 0, left: 0 };
if(typeof elem.getBoundingClientRect !== "undefined") box =
elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) -
(document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) -
(document.clientTop || 0)
};
},
I am trying to get the DOM element visibility percentage from document viewport.
I've modified few lines to work code and it's working fine.
Check below fiddle
https://jsfiddle.net/darjiyogen/q16c1m7s/1/
'use strict';
var results = {};
function display() {
var resultString = '';
$.each(results, function(key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});
$('p').text(resultString);
}
function calculateVisibilityForDiv(div$) {
debugger;
div$ = div$[0];
var windowHeight = window.innerHeight || document.documentElement.clientHeight,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = {
top: 0,
left: 0
};
if (typeof elem.getBoundingClientRect !== "undefined") box = elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0)
};
};
function calculateAndDisplayForAllDivs() {
$('div').each(function() {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});
display();
}
$(document).scroll(function() {
calculateAndDisplayForAllDivs();
});
$(document).ready(function() {
calculateAndDisplayForAllDivs();
});
div {
height: 300px;
width: 300px;
border-width: 1px;
border-style: solid;
}
p {
position: fixed;
left: 320px;
top: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>
The issue that I am having is getting my sticky nav to span the entire width of the page. I am using the jquery sticky nav plugin from http://stickyjs.com/ - I have tried setting the width to 100% but there is an element.style property that is overriding the containers width. After researching this issue it seems that this element.style value comes from the javascript for this plugin. I am new to code and I have limited javascript knowledge so any guidance on how to change/remove that element.style value would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.sticky.js"></script>
</head>
<body>
<div class="wrapper">
<header id="sticker" class="clearfix">
<img src="img/logo.png" alt="Conference Logo">
<nav>
<ul class="monquan">
<li>Schedule</li>
<li>Locations</li>
<li>Workshops</li>
<li>Register</li>
</ul>
</nav>
</header>
</div>
<script>
$(document).ready(function(){
$("#sticker").sticky({topSpacing:0});
});
</script>
</body>
</html>
There is the HTML for my project and below is the jquery.sticky.js code that I believe holds the answer to my problem.
// Sticky Plugin v1.0.4 for jQuery
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Improvements by Leonardo C. Daronco (daronco)
// Created: 02/14/2011
// Date: 07/20/2015
// Website: http://stickyjs.com/
// Description: Makes an element on the page stick on the screen as you scroll
// It will only set the 'top' and 'position' of your element, you
// might need to adjust the width in some cases.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var slice = Array.prototype.slice; // save ref to original slice()
var splice = Array.prototype.splice; // save ref to original slice()
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
wrapperClassName: 'sticky-wrapper',
center: false,
getWidthFrom: '',
widthFromWrapper: true, // works only when .getWidthFrom is empty
responsiveWidth: false,
zIndex: 'auto'
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0, l = sticked.length; i < l; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra;
//update height in case of dynamic content
s.stickyWrapper.css('height', s.stickyElement.outerHeight());
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement
.css({
'width': '',
'position': '',
'top': '',
'z-index': ''
});
s.stickyElement.parent().removeClass(s.className);
s.stickyElement.trigger('sticky-end', [s]);
s.currentTop = null;
}
}
else {
var newTop = documentHeight - s.stickyElement.outerHeight()
- s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop < 0) {
newTop = newTop + s.topSpacing;
} else {
newTop = s.topSpacing;
}
if (s.currentTop !== newTop) {
var newWidth;
if (s.getWidthFrom) {
newWidth = $(s.getWidthFrom).width() || null;
} else if (s.widthFromWrapper) {
newWidth = s.stickyWrapper.width();
}
if (newWidth == null) {
newWidth = s.stickyElement.width();
}
s.stickyElement
.css('width', newWidth)
.css('position', 'fixed')
.css('top', newTop)
.css('z-index', s.zIndex);
s.stickyElement.parent().addClass(s.className);
if (s.currentTop === null) {
s.stickyElement.trigger('sticky-start', [s]);
} else {
// sticky is started but it have to be repositioned
s.stickyElement.trigger('sticky-update', [s]);
}
if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) {
// just reached bottom || just started to stick but bottom is already reached
s.stickyElement.trigger('sticky-bottom-reached', [s]);
} else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) {
// sticky is started && sticked at topSpacing && overflowing from top just finished
s.stickyElement.trigger('sticky-bottom-unreached', [s]);
}
s.currentTop = newTop;
}
// Check if sticky has reached end of container and stop sticking
var stickyWrapperContainer = s.stickyWrapper.parent();
var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + stickyWrapperContainer.outerHeight()) && (s.stickyElement.offset().top <= s.topSpacing);
if( unstick ) {
s.stickyElement
.css('position', 'absolute')
.css('top', '')
.css('bottom', 0)
.css('z-index', '');
} else {
s.stickyElement
.css('position', 'fixed')
.css('top', newTop)
.css('bottom', '')
.css('z-index', s.zIndex);
}
}
}
},
resizer = function() {
windowHeight = $window.height();
for (var i = 0, l = sticked.length; i < l; i++) {
var s = sticked[i];
var newWidth = null;
if (s.getWidthFrom) {
if (s.responsiveWidth) {
newWidth = $(s.getWidthFrom).width();
}
} else if(s.widthFromWrapper) {
newWidth = s.stickyWrapper.width();
}
if (newWidth != null) {
s.stickyElement.css('width', newWidth);
}
}
},
methods = {
init: function(options) {
var o = $.extend({}, defaults, options);
return this.each(function() {
var stickyElement = $(this);
var stickyId = stickyElement.attr('id');
var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName;
var wrapper = $('<div></div>')
.attr('id', wrapperId)
.addClass(o.wrapperClassName);
stickyElement.wrapAll(function() {
if ($(this).parent("#" + wrapperId).length == 0) {
return wrapper;
}
});
var stickyWrapper = stickyElement.parent();
if (o.center) {
stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
}
if (stickyElement.css("float") === "right") {
stickyElement.css({"float":"none"}).parent().css({"float":"right"});
}
o.stickyElement = stickyElement;
o.stickyWrapper = stickyWrapper;
o.currentTop = null;
sticked.push(o);
methods.setWrapperHeight(this);
methods.setupChangeListeners(this);
});
},
setWrapperHeight: function(stickyElement) {
var element = $(stickyElement);
var stickyWrapper = element.parent();
if (stickyWrapper) {
stickyWrapper.css('height', element.outerHeight());
}
},
setupChangeListeners: function(stickyElement) {
if (window.MutationObserver) {
var mutationObserver = new window.MutationObserver(function(mutations) {
if (mutations[0].addedNodes.length || mutations[0].removedNodes.length) {
methods.setWrapperHeight(stickyElement);
}
});
mutationObserver.observe(stickyElement, {subtree: true, childList: true});
} else {
if (window.addEventListener) {
stickyElement.addEventListener('DOMNodeInserted', function() {
methods.setWrapperHeight(stickyElement);
}, false);
stickyElement.addEventListener('DOMNodeRemoved', function() {
methods.setWrapperHeight(stickyElement);
}, false);
} else if (window.attachEvent) {
stickyElement.attachEvent('onDOMNodeInserted', function() {
methods.setWrapperHeight(stickyElement);
});
stickyElement.attachEvent('onDOMNodeRemoved', function() {
methods.setWrapperHeight(stickyElement);
});
}
}
},
update: scroller,
unstick: function(options) {
return this.each(function() {
var that = this;
var unstickyElement = $(that);
var removeIdx = -1;
var i = sticked.length;
while (i-- > 0) {
if (sticked[i].stickyElement.get(0) === that) {
splice.call(sticked,i,1);
removeIdx = i;
}
}
if(removeIdx !== -1) {
unstickyElement.unwrap();
unstickyElement
.css({
'width': '',
'position': '',
'top': '',
'float': '',
'z-index': ''
})
;
}
});
}
};
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(method) {
if (methods[method]) {
return methods[method].apply(this, slice.call(arguments, 1));
} else if (typeof method === 'object' || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error('Method ' + method + ' does not exist on jQuery.sticky');
}
};
$.fn.unstick = function(method) {
if (methods[method]) {
return methods[method].apply(this, slice.call(arguments, 1));
} else if (typeof method === 'object' || !method ) {
return methods.unstick.apply( this, arguments );
} else {
$.error('Method ' + method + ' does not exist on jQuery.sticky');
}
};
$(function() {
setTimeout(scroller, 0);
});
}));
Please let me know if there is anything else I can provide to make answering this easier and I appreciate any input.
I strongly suggest not to change the library file, it will pretty much defeat the purpose of you using a library in the first place. A library is designed to work in a specific way and mostly follows a rigid code, meaning if you change a single component the repercussions might be bad or worse non-debuggable.
If you want, you must always override the code with your own custom files. In your case, after the <script src="js/jquery.sticky.js"></script> create a js file of your own say, <script src="js/custom.js"></script> and add this there(this is just a basic example)
element.css({"width":"100%"});
OR adding the same line onto your internal <script> in your HTML(where you have initiated the stickybar) will also work well.
I am trying to center a DIV in screen using below code but it is not working for me. Someone please suggest me to make it work
var hnw = {};
hnw.w = 0;
hnw.h = 0;
if (!window.innerWidth) {
if (!(document.documentElement.clientWidth == 0)) {
hnw.w = document.documentElement.clientWidth;
hnw.h = document.documentElement.clientHeight;
}
else {
hnw.w = document.body.clientWidth;
hnw.h = document.body.clientHeight;
}
}
else {
hnw.w = window.innerWidth;
hnw.h = window.innerHeight;
}
var midEle = document.createElement('div');
var _x = 0;
var _y = 0;
var offsetX = 0;
var offsetY = 0;
if (!window.pageYOffset) {
if (!(document.documentElement.scrollTop == 0)) {
offsetY = document.documentElement.scrollTop;
offsetX = document.documentElement.scrollLeft;
}
else {
offsetY = document.body.scrollTop;
offsetX = document.body.scrollLeft;
}
}
else {
offsetX = window.pageXOffset;
offsetY = window.pageYOffset;
}
midEle.style.width = "300px";
midEle.style.height = "300px";
midEle.innerHTML = "Some Text";
midEle.style.display = "block";
var _x_w = parseInt(midEle.style.width, 10), _y_h = parseInt(midEle.style.height, 10);
_x = ((hnw.w - _x_w) / 2) + offsetX;
_y = ((hnw.h - _y_h) / 2) + offsetY;
console.log(_x, " ", _y);
midEle.style.position = "absolute";
midEle.style.left = _x;
midEle.style.top = _y;
document.body.appendChild(midEle);
Can't this be done with CSS instead?
Javascript:
var midEle = document.createElement('div');
midEle.className = 'centered';
document.body.appendChild(midEle);
​CSS:
​.centered{
background-color: red;
height: 300px;
width: 300px;
margin: -150px 0 0 -150px;
top: 50%;
left: 50%;
position: fixed;
}​
http://jsfiddle.net/FkEyy/3/
By setting the margins to the negative half of the elements height and width, and setting top and left values to 50%, you'll center the element. This is a common way of centering content with CSS :)
For left and top style properties px was missing. Values must be either px or %
Change
midEle.style.left = _x;
midEle.style.top = _y;
To
midEle.style.left = _x+"px";
midEle.style.top = _y+"px";
Demo: http://jsfiddle.net/muthkum/AFkKt/
Here is a demo if you want to center something in the browser viewport using vanilla JavaScript.
http://jsfiddle.net/CDtGR/5/
<html>
<!--measure size of elements,
get absolute position of elements,
get viewport size and scrollposition-->
<script>
var mesr =
{
Metrics: {
px: 1,
measureUnits: function(target) {
if(typeof(target) == 'undefined')
target = document.getElementsByTagName('body')[0];
mesr.Metrics.measureUnit("em", target);
mesr.Metrics.measureUnit("pt", target);
mesr.Metrics.measureUnit("%", target);
},
measureUnit: function(unit, target) {
if(typeof(target.Metrics) == 'undefined')
target.Metrics = {};
var measureTarget = target;
if(target.tagName == 'IMG' && typeof(target.parentNode) != 'undefined')
measureTarget = target.parentNode;
var measureElement = document.createElement("div");
measureElement.style.width = "1"+unit;
measureElement.style.cssFloat = "left";
measureElement.style.styleFloat = "left";
measureElement.style.margin = "0px";
measureElement.style.padding = "0px";
measureTarget.appendChild(measureElement);
target.Metrics[unit] = measureElement.offsetWidth;
measureElement.parentNode.removeChild(measureElement);
return target.Metrics[unit];
},
getUnitPixels: function(unitString, target) {
if(typeof(target) == 'undefined')
target = document.getElementsByTagName('body')[0];
if(typeof(target.Metrics) == 'undefined')
mesr.Metrics.measureUnits(target);
var unit = unitString.replace(/[0-9\s]+/ig,'').toLowerCase();
var size = Number(unitString.replace(/[^0-9]+/ig,''));
if(typeof(target.Metrics[unit]) == 'undefined')
return 0;
var metricSize = target.Metrics[unit];
var pixels = Math.floor(Number(metricSize * size));
return pixels;
}
},
getElementOffset: function(target) {
var pos = [target.offsetLeft,target.offsetTop];
if(target.offsetParent != null) {
var offsetPos = mesr.getElementOffset(target.offsetParent);
pos = [
pos[0] + offsetPos[0],
pos[1] + offsetPos[1]
];
}
return pos;
},
getElementPosition: function(target) {
var offset = mesr.getElementOffset(target);
var x = offset[0] +
mesr.Metrics.getUnitPixels(target.style.paddingLeft, target) +
mesr.Metrics.getUnitPixels(target.style.borderLeftWidth, target);
var y = offset[1] +
mesr.Metrics.getUnitPixels(target.style.paddingTop, target) +
mesr.Metrics.getUnitPixels(target.style.borderTopWidth, target);
return [x,y];
},
getElementSize: function(target) {
var size = [target.offsetWidth, target.offsetHeight];
size[0] -= mesr.Metrics.getUnitPixels(target.style.paddingLeft, target) +
mesr.Metrics.getUnitPixels(target.style.paddingRight, target) +
mesr.Metrics.getUnitPixels(target.style.borderLeftWidth, target) +
mesr.Metrics.getUnitPixels(target.style.borderRightWidth, target);
size[1] -= mesr.Metrics.getUnitPixels(target.style.paddingTop, target) +
mesr.Metrics.getUnitPixels(target.style.paddingBottom, target) +
mesr.Metrics.getUnitPixels(target.style.borderTopWidth, target) +
mesr.Metrics.getUnitPixels(target.style.borderBottomWidth, target);
return size;
},
getViewPortSize: function () {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return [myWidth, myHeight];
},
getViewPortScrollPosition: function () {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
},
attachEvent : function(target, eventList, func) {
if(typeof (target) == "undefined" || target == null)
return;
var events = eventList.split(",");
for(var i=0;i<events.length;i++) {
var event = events[i];
if(typeof(target.addEventListener) != 'undefined') {
target.addEventListener(event, func);
} else if(typeof(target.attachEvent) != 'undefined') {
target.attachEvent('on'+event,func);
} else {
console.log("unable to attach event listener");
}
}
}
}
</script>
<!--positioning-->
<script>
function position(){
var viewPortSize = mesr.getViewPortSize();
var viewPortScrollPos = mesr.getViewPortScrollPosition();
var size = mesr.getElementSize(document.getElementById('apa'));
document.getElementById('apa').style.left = Math.floor((viewPortSize[0]/2)-(size[0]/2)+viewPortScrollPos[0])+"px";
document.getElementById('apa').style.top = Math.floor((viewPortSize[1]/2)-(size[1]/2)+viewPortScrollPos[1])+"px";
}
mesr.attachEvent(window,"resize,scroll,load",position);
mesr.attachEvent(document,"load",position);
</script>
<body>
<div id="apa" style="position:absolute;">some text</div>
</body>
</html>
I'm trying to get previous and current window width via JS. I use jQuery for capturing window resize event. Here's my code:
<script>
function getWindowWidth() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth; myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
}
return myWidth;
}
var lastWindowWidth;
$(document).ready(function() {
$(window).resize(function() {
$('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + getWindowWidth());
lastWindowWidth = getWindowWidth();
});
});
</script>
It returns me:
Previous: 1685 Current: 1685
Why both Previous: and Current: values are similar? Thanks in advance!
You are using jQuery.
So use jQuery:
$(window).width();
var lastWindowWidth;
$(document).ready(function() {
$(window).resize(function() {
var $window = $(this),
windowWidth = $window.width();
$('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + windowWidth );
lastWindowWidth = windowWidth;
});
});
Fiddle: http://jsfiddle.net/maniator/pKfSN/5/
The essence of the answer is to capture the previous_window_width before the window is resized:
var previous_window_width = $(window).width();
...
$(window).resize(function() {
var current_window_width = $(window).width();
// do whatever you need with previous_window_width
});
here you go http://jsfiddle.net/B9chY/
var lastWindowWidth = $(window).width();
$(window).resize(function() {
$('#h1_text').text("Previous: "+ lastWindowWidth + " Current: " + $(window).width());
lastWindowWidth = $(window).width();
});
based on comments:
var lessThan = false;
$(document).ready(function() {
if ($(window).width() < 980) {
lessThan = true;
}
});
$(window).resize(function() {
if ($(window).width() < 980) {
lessThan = true;
}
});