Restricting the position of an image to the viewable area in javascript? - javascript

So I have this script to move around an image. But I want to make it so I cant move the bottom of the image above the bottom 60 pixels.
function right(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1; // get just the number and not the units
document.getElementById(id).style.left = current - 5 + 'px'; // taking advantage of JavaScript's strange but sometimes useful type conversion. The subtraction converts it to an int and the addition converts it back to a string.
document.getElementById(id).src = 'guyr.png'
}
function left(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1;
document.getElementById(id).style.left = parseInt(current) + 5 + 'px'; // here we can't use that trick
}
function up(id) {
document.getElementById(id).style.top.match(/^([0-9]+)/);
var current = RegExp.$1;
document.getElementById(id).style.top = current - 5 + 'px';
}
function down(id) {
document.getElementById(id).style.top.match(/^([0-9]+)/);
var current = RegExp.$1;
document.getElementById(id).style.top = parseInt(current) + 5 + 'px';
}

First, you have to detect the height of browser:
var myHeight;
if( typeof( window.innerHeight ) == 'number' ) {
//Non-IE
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientHeight ) ) {
//IE 4 compatible
myHeight = document.body.clientHeight;
}
Then, you can set condition :
if(current > myHeight - 60) {
// do your function
}

Related

Parallax Background Positioning Scrolling

I have just developed a new parallax scrolling script. I have it working just the way I want however there is just 1 issue with it currently.
I want the script to start scrolling the background image at the y coord that is specified in the css stylesheet by default. Instead my script seems to be resetting the CSS y coord to 0 before scrolling the image. This is obviously undesired behavior.
// Parallax scripting starts here
$.prototype.jpayParallax = function(userOptions){
var _api = {};
_api.utils = {};
_api.utils.isElementInViewport = function(el){
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
_api.utils.debounceScrollWheel = (function(){
$(function(){
var $window = $(window); //Window object
var scrollTime = 0.3; //Scroll time
var scrollDistance = 50; //Distance. Use smaller value for shorter scroll and greater value for longer scroll
$window.on("mousewheel DOMMouseScroll", function(event){
event.preventDefault();
var delta = event.originalEvent.wheelDelta/120 || -event.originalEvent.detail/3;
var scrollTop = $window.scrollTop();
var finalScroll = scrollTop - parseInt(delta*scrollDistance);
TweenMax.to($window, scrollTime, {
scrollTo : { y: finalScroll, autoKill:true },
ease: Power1.easeOut, //For more easing functions see http://api.greensock.com/js/com/greensock/easing/package-detail.html
autoKill: true,
overwrite: 5
});
});
});
})();
_api.selector = 'data-jpay-parallax';
_api.methods = {};
_api.methods.checkForVisibleParallaxEls = function(){
$('['+_api.selector+']').each(function(){
var instanceObject = $(this);
var origBgPos = $(this).css('backgroundPosition').split(' ');
var options = $(this).data('jpay-parallax');
console.log(origBgPos)
if (_api.utils.isElementInViewport(instanceObject)){
_api.methods.doParallax(instanceObject, options);
}
});
}
_api.methods.doParallax = function(instanceToManip, userOptions){
var direction = userOptions.settings.direction;
var orientation = userOptions.settings.orientation;
var speed = userOptions.settings.speed;
var type = userOptions.settings.type;
var speedInt;
var getSpeed = (function(){
if (speed){
switch(speed){
case 'slow':
speedInt = 10;
break;
case 'fast':
speedInt = 5;
break;
case 'faster':
speedInt = 1;
break;
default:
throw new TypeError('Unknown speed parameter added to module instructions');
}
}
})();
var distToTopInt = function(){
if (typeof speedInt === 'number'){
return $(window).scrollTop()/speedInt;
}
else {
return $(window).scrollTop();
}
}
var origPos = instanceToManip.css('backgroundPosition').split(' ');
var origPosX = parseInt(origPos[0]);
var origPosY = parseInt(origPos[1]);
var newPosY = origPosY += distToTopInt();
var newPosX = origPosX += distToTopInt();
if (orientation === 'vertical' && direction !== 'reverse'){
instanceToManip.css('backgroundPositionY', newPosX+'px');
}
else if (orientation === 'vertical' && direction === 'reverse'){
instanceToManip.css('backgroundPositionY', -newPosX+'px');
}
else if (orientation == 'horizontal' && direction !== 'reverse'){
instanceToManip.css('backgroundPositionX', newPosX+'px');
}
else if (orientation == 'horizontal' && direction === 'reverse'){
instanceToManip.css('backgroundPositionX', -newPosY+'px');
}
}
$(window).on('scroll', _api.methods.checkForVisibleParallaxEls)
};
$.fn.jpayParallax();
Here is the pen:
http://codepen.io/nicholasabrams/pen/OPxKXm/?editors=001
BONUS: Why does this script also mess with the css set backgroundSize property when the script never accesses it?
I am looking for advice in where in the script to cache the original CSS background image y coord value so that it becomes incremented from there instead of starting at 0px /0 for each instance. Thanks again for the help!

make message always on the top

i want to make a message which will be always on the top however scrolling the page using java script.
i tried the below code, but when i scroll it still on its static place
var message = '<b><font color=000000 size=5>mona link to us! </font></b>'
//enter a color name or hex to be used as the background color of the message
var backgroundcolor = "#FFFF8A"
//enter 1 for always display, 2 for ONCE per browser session
var displaymode = 1
//Set duration message should appear on screen, in seconds (10000=10 sec, 0=perpetual)
var displayduration = 0
//enter 0 for non-flashing message, 1 for flashing
var flashmode = 1
//if above is set to flashing, enter the flash-to color below
var flashtocolor = "lightyellow"
var ie = document.all
var ieNOTopera = document.all && navigator.userAgent.indexOf("Opera") == -1
function regenerate() {
window.location.reload()
}
function regenerate2() {
if (document.layers)
setTimeout("window.onresize=regenerate", 400)
}
var which = 0
function flash() {
if (which == 0) {
if (document.layers)
topmsg_obj.bgColor = flashtocolor
else
topmsg_obj.style.backgroundColor = flashtocolor
which = 1
}
else {
if (document.layers)
topmsg_obj.bgColor = backgroundcolor
else
topmsg_obj.style.backgroundColor = backgroundcolor
which = 0
}
}
if (ie || document.getElementById)
document.write('<div id="topmsg" style="position:absolute;visibility:hidden">' + message + '</div>')
var topmsg_obj = ie ? document.all.topmsg : document.getElementById ? document.getElementById("topmsg") : document.topmsg
function positionit() {
var dsocleft = ie ? document.body.scrollLeft : pageXOffset
var dsoctop = ie ? document.body.scrollTop : pageYOffset
var window_width = ieNOTopera ? document.body.clientWidth : window.innerWidth - 20
var window_height = ieNOTopera ? document.body.clientHeight : window.innerHeight
if (ie || document.getElementById) {
topmsg_obj.style.left = parseInt(dsocleft) + window_width / 2 - topmsg_obj.offsetWidth / 2
topmsg_obj.style.top = parseInt(dsoctop) + parseInt(window_height) - topmsg_obj.offsetHeight - 4
}
else if (document.layers) {
topmsg_obj.left = dsocleft + window_width / 2 - topmsg_obj.document.width / 2
topmsg_obj.top = dsoctop + window_height - topmsg_obj.document.height - 5
}
}
function setmessage() {
if (displaymode == 2 && (!display_msg_or_not()))
return
if (document.layers) {
topmsg_obj = new Layer(window.innerWidth)
topmsg_obj.bgColor = backgroundcolor
regenerate2()
topmsg_obj.document.write(message)
topmsg_obj.document.close()
positionit()
topmsg_obj.visibility = "show"
if (displayduration != 0)
setTimeout("topmsg_obj.visibility='hide'", displayduration)
}
else {
positionit()
topmsg_obj.style.backgroundColor = backgroundcolor
topmsg_obj.style.visibility = "visible"
if (displayduration != 0)
setTimeout("topmsg_obj.style.visibility='hidden'", displayduration)
}
setInterval("positionit()", 100)
if (flashmode == 1)
setInterval("flash()", 1000)
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = ""
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset)
if (end == -1)
end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function display_msg_or_not() {
if (get_cookie("displaymsg") == "") {
document.cookie = "displaymsg=yes"
return true
}
else
return false
}
if (document.layers || ie || document.getElementById)
window.onload = setmessage
any help. or any new code please
If I'm understanding what you want, I think you're totally over thinking it. You can use CSS to keep your message fixed at the top of the page. just add position: fixed. It's how I make my header stay at the top of the page on this site: http://www.recipegraze.com
So use javascript to make the message appear/disappear, but use some simple CSS to make it stick to the top of the page.
edit: you'll also want to up the z-index of the message to make sure it appears on top of your other content, not under it.

How to collect characters/word typed next to # or # in div

I have a div with its contenteditable property set to true. When user types '#' or '#', I would like to get whatever he/she type until spacebar is pressed. This way, I can bring suggestions from db according to the word he/she may type.
Please have a look at example below,
<div id="editableDiv" contenteditable="true">
I may tweet from #twitter in the near #future
<ul id="suggestUL"></ul>
</div>
As soon as user type '#' or '#', I must be able to collect whatever he/she may type (according to above example, after # t, tw, twi, twit, twitt, twitte and twitter. And after # f, fu... future). After 'twitter', user typed spacebar so, the word collection must stop and must start from # again.
Edited
Code to get the pixel where I could display suggestion list
function getCaretPixelPos($node) {
var offsetx = 0;
var offsety = 0;
var nodeLeft = 0,
nodeTop = 0;
if ($node) {
nodeLeft = $node.offsetLeft;
nodeTop = $node.offsetTop;
}
var pos = { left: 0, top: 0 };
if (document.selection) {
var range = document.selection.createRange();
pos.left = range.offsetLeft + offsetx - nodeLeft + 'px';
pos.top = range.offsetTop + offsety - nodeTop + 'px';
} else if (window.getSelection) {
var sel = window.getSelection();
var range = sel.getRangeAt(0).cloneRange();
try {
range.setStart(range.startContainer, range.startOffset - 1);
} catch (e) { }
var rect = range.getBoundingClientRect();
if (range.endOffset == 0 || range.toString() === '') {
// first char of line
if (range.startContainer == $node) {
// empty div
if (range.endOffset == 0) {
pos.top = '0px';
pos.left = '0px';
} else {
// firefox need this
var range2 = range.cloneRange();
range2.setStart(range2.startContainer, 0);
var rect2 = range2.getBoundingClientRect();
pos.left = rect2.left + offsetx - nodeLeft + 'px';
pos.top = rect2.top + rect2.height + offsety - nodeTop + 'px';
}
} else {
pos.top = range.startContainer.offsetTop + 'px';
pos.left = range.startContainer.offsetLeft + 'px';
}
} else {
pos.left = rect.left + rect.width + offsetx - nodeLeft + 'px';
pos.top = rect.top + offsety - nodeTop + 'px';
}
}
//console.log('pos left : ' + pos.left + ' pos top : ' + pos.top);
//console.log($('#suggestUL'));
$('#suggestUL').css('left', pos.left);
$('#suggestUL').css('top', pos.top);
//console.log('suggestUL left : ' + $('#suggestUL').css('left') + ' suggestUL top : ' + $('#suggestUL').css('top'));
};
This is how I am calling above function
var event = e || window.event;
var keyCode = event.keyCode || event.which;
if (keyCode == 35 || keyCode == 64)
getCaretPixelPos($('#editableDiv')[0]);
PS: I don't know why I have been fined by -2 reputation for Title. Anyway I edited title for more clarity. I am a learner, If I do any mistake in choosing title or asking question, kindly do suggest.
Thanks in advance.
You can use following script, along with this you need to use some UL/LI element combination which will show one suggestion per line, once data is fetched from the sever. You can use the jQuery Ajax to to fetch the data from sever and create the ul/li list dynamically.
var fetchData = false;
var suggestionChar = '';
$('#editableDiv').on('keypress',function(event){
var keyCode = event.which || event.keyCode.
var hashKey; // Set keyCode for #
var atKey; // Set keycode for #
var spaceKey //SpaceKey code
if(keyCode == hashKey || keyCode == atKey){
fetchData = true
suggestionChar = '';
return; //flag is set now look out for next key cod.
}
else if ( keyCode == spaceKey ){
fetchData = false;
suggestionChar = '';
}
if( fetchData){
var data = String.fromCharCode(keyCode);
suggestionChar = suggestionChar + data;
// use "suggestionChar" for fetching the data from server.
// fetch suggestions from Server.
// On success call back create the dynamic list of ul/li which will show the suggestion to user. You need to bind the user click event and/or keypress event for ul/li so that user can select the suggestion using mouse and keyboard along with 'Space' key.
}
})
I've made this stuff (textarea only) : http://jsfiddle.net/wared/sL2sZ/. I've tried to match your requirements but it's a bit more time-consuming to make things work using an editable DIV. I've decided to give up and to take inspiration from StackOverflow. You might pick up some ideas from my code in order to achieve your goal, hopefully.
More on getCaret() here : https://stackoverflow.com/a/263796/1636522.
Shirt-tail...
Currently, you are able to get the pixel position of the caret, while my code brings you a way to get the word around the current caret index. The missing link is a cross-browser solution to get the caret index from an editable DIV (this is where I gave up, too much work for me), indeed, the current version of getCaret() only accepts a textarea.
In other words, all you have to do is to modify the body of getCaret() in order to make it work with an editable DIV. Once you have the index, you have the word around it through getWord(), so, you can check if it's prefixed with "#", then display appropriate suggestions using getCaretPixelPos().
$('textarea').on('click keyup', function isAt() {
var idx = getCaret(this),
text = $(this).val(),
word = getWord(text, idx);
$('p').html([
'"', word, '" ', word.charAt(0) === '#'
? '<span style="color:blue">is prefixed</span>'
: '<span style="color:red">is not prefixed</span>'
].join(''));
}).focus();
function getWord(s, i) {
var r = /\s/g;
if (!i || r.test(s[i - 1])) return '';
while (i && !r.test(s[--i])) {}
r.lastIndex = i && ++i;
return s.slice(i, (
r.exec(s) || { index: s.length }
).index);
}
Try this:
var str = '';
$('#editableDiv').keyup(function(e){
if($(this).val() == '#' || $(this).val() == "#"){
if(e.keyCode !=32){
str += String.fromCharCode(e.keyCode);
}
}
});
alert(str);
I was finally able to solve the issue from all of your inputs.
Here is the code
Function called on KeyDown
var fetchSuggestions = false;
var suggestForString = '';
function fnShowSuggestionUL(e) {
var event = e || window.event;
var keyCode = event.keyCode || event.which;
// KeyCode = 35 -> #
// KeyCode = 64 -> #
// KeyCode = 32 -> space
// KeyCode = 13 -> Enter (Carriage Return)
if (keyCode == 35 || keyCode == 64) {
fetchSuggestions = true;
suggestForString = '';
$('#suggestUL').css('display', 'block');
fnPositionSuggestUL();
}
else if (keyCode == 32 || keyCode == 13) {
fetchSuggestions = false;
suggestForString = '';
$('#suggestUL').css('display', 'none');
return;
}
if (fetchSuggestions == false)
return;
var data = String.fromCharCode(keyCode);
suggestForString = suggestForString + data;
// TODO: bring suggestions from database and append them as list items to "suggestUL"
}
Position suggestUL at character '#' or '#'
function fnPositionSuggestUL() {
var $node = $('#editableDiv')[0]
var offsetx = 0;
var offsety = 0;
var nodeLeft = 0,
nodeTop = 0;
if ($node) {
nodeLeft = $node.offsetLeft;
nodeTop = $node.offsetTop;
}
var pos = { left: 0, top: 0 };
if (document.selection) {
var range = document.selection.createRange();
pos.left = range.offsetLeft + offsetx - nodeLeft + 'px';
pos.top = range.offsetTop + offsety - nodeTop + 'px';
} else if (window.getSelection) {
var sel = window.getSelection();
var range = sel.getRangeAt(0).cloneRange();
try {
range.setStart(range.startContainer, range.startOffset - 1);
} catch (e) { }
var rect = range.getBoundingClientRect();
if (range.endOffset == 0 || range.toString() === '') {
// first char of line
if (range.startContainer == $node) {
// empty div
if (range.endOffset == 0) {
pos.top = '0';
pos.left = '0';
} else {
// firefox need this
var range2 = range.cloneRange();
range2.setStart(range2.startContainer, 0);
var rect2 = range2.getBoundingClientRect();
pos.left = rect2.left + offsetx - nodeLeft;
pos.top = rect2.top + rect2.height + offsety - nodeTop;
}
} else {
pos.top = range.startContainer.offsetTop;
pos.left = range.startContainer.offsetLeft;
}
} else {
pos.left = rect.left + rect.width + offsetx - nodeLeft;
pos.top = rect.top + offsety - nodeTop;
}
}
//Create suggestUL if does not exist or destroyed
fnCreateSuggestUL();
$('#suggestUL').css('left', pos.left + 'px').css('top', (pos.top + 18)+'px');
};
I would like to thank one and all who answered/commented here.
Please optimize above code as much as possible so that one who in need gets perfect code.
PS: Works perfect in Chrome and firefox. suggestUL is not properly positioning in IE.
Happy Coding!!

Centering a DIV in viewport with JavaScript

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>

Get previous and current window width

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;
}
});

Categories

Resources