JavaScript - how do i get currentStyle of the element in Opera - javascript

i'm trying to get fontWeight property of the strong element in opera. and i'm stuck. this is my function:
getCurrentStyle: function (el, styleProp) {
if (!el || !styleProp) return ''
styleProp = pinecf.unifyStyleProp(styleProp)
var y = '',
st
try {
st = pinecf.getElementStyle(el)
} catch (e) {}
alert($(el).css(styleProp.replace(/([A-Z])/g, '-$1').toLowerCase()))
if (pinecf.CAE(st, styleProp)) y = st[styleProp]
else try {
if (el.currentStyle) y = el.currentStyle[styleProp];
else if (pine.window.getComputedStyle) y = pine.document.defaultView.getComputedStyle(el, null)[styleProp]
} catch (e) {
try {
y = $(el).css(styleProp.replace(/([A-Z])/g, '-$1').toLowerCase())
} catch (e) {}
}
if (styleProp == 'fontWeight' && parseInt(y) > 0) {
if (y > 400) y = 'bold'
else y = 'normal'
} else if (styleProp == 'fontSize' && y && y.search(/pt/i) != -1) y = parseInt(y) * 1.33
if (!y) y = ''
return typeof y == 'string' ? pinecf.trim(y).toLowerCase() : y
}
and it allways return empty value whatever method i try.
please tell me how to get real value of currentStyle in Opera browser.
any help appriciated!

Isn't the getComputedStyle() part of the window object not the document?
I got it to work using this
for(i = 0, el = document.getElementsByTagName("strong") ; i < el.length; i++)
{
cssProp = window.getComputedStyle(el[i], "cssText");
//cssProp = window.getComputedStyle(el[i], null); to get all the computed css styles
console.log(cssProp["fontWeight"])
}

Related

.getValues cannot read Custom Function

I have to create automated reports with Google Apps Script for an internal client. Straight forward: retrive data, manipulate data, some if tests, and print data in a new format.
My problem is, the source of the data uses a custom function (also designed by me, for date calculation) that is pretty complex, and it is essential for the client, and, apparently, I cannot retrieve the data with the method .getValues from custom functions.
This is the error I get:
9:42:41 AM Error Exception: Cannot convert 'function () { [native code] }' to int.
ARROBA # Scripts Automáticos.gs:5
Is this a real problem in GAS, and is there any workaround this? Or, better, have I coded something wrong? I tried indirect references (like instead of getting the data directly from the custom function, getting it from other cells that referenced that data) but it didn't work.
Here is the line where the problem occurs:
var data = ss.getRange(2, 1, ss.getLastRow, ss.getLastColumn).getValues
Here is on example of codes that do not work:
function ARROBA() {
var ss = SpreadsheetApp.openById([ID]).getSheetByName([sheet])
var data = ss.getRange(2, 1, ss.getLastRow, ss.getLastColumn).getValues
var today = new Date()
var x
var y
for (x = 0; x < data.length; x++) {
if (data[x][34] == "Sim") {
ss.getRange(x+2,7).setValue(data[x][7]+"\n#\n"+(today.getDay+'/'+today.getMonth+'/'+today.getFullYear))
ss.getRange(x+2,34).setValue()
ss.getRange(x+2,35).setValue(data[x][35]+"\n#\n")
ss.getRange(x+2,36).setValue(data[x][36]+"\n#\n")
ss.getRange(x+2,37).setValue(data[x][37]+"\n#\n")
ss.getRange(x+2,38).setValue(data[x][38]+"\n#\n")
}
}
}
And here is the Custom Function:
function SLABANKING (start, startcongelamento, finalcongelamento, startdeclinio, finaldeclinio, cancelamento, end) {
var today = new Date();
var congelamento = 0
var declinio = 0
var x
var y
var z
var s
//typing error handling
if (start == null || start == '') {
return 'Necessário incluir data de início'
} else if(startcongelamento.toString.length != finalcongelamento.toString.length && startcongelamento.toString.length - finalcongelamento.toString.length != 11) {
return 'Erro de preenchimento de datas de congelamento'
} else if(startdeclinio.toString.length != finaldeclinio.toString.length && startdeclinio.toString.length - finaldeclinio.toString.length != 11) {
return 'Erro de preenchimento de datas de reabertura'
} else {
//set de variáveis + complexas
if(startcongelamento.toString().lastIndexOf('#') < 0) {
var sconge = startcongelamento.toString().split('\n')
var fconge = finalcongelamento.toString().split('\n')
var sdec = startdeclinio.toString().split('\n')
var fdec = finaldeclinio.toString().split('\n')
} else {
var sconge = startcongelamento.toString().slice(startcongelamento.toString().lastIndexOf('#')+2, startcongelamento.length).split('\n')
var fconge = finalcongelamento.toString().slice(finalcongelamento.toString().lastIndexOf('#')+2, finalcongelamento.length).split('\n')
var sdec = startdeclinio.toString().slice(startdeclinio.toString().lastIndexOf('#')+2, startdeclinio.length).split('\n')
var fdec = finaldeclinio.toString().slice(finaldeclinio.toString().lastIndexOf('#')+2, finaldeclinio.length).split('\n')
}
//congelamento
if(startcongelamento == null || startcongelamento == undefined || startcongelamento == ''){
} else if(startcongelamento.length != finalcongelamento.length) {
if (startcongelamento.length > 10 && finalcongelamento.length > 10) {
Logger.log('desigual, start e final > 10')
var display = []
for (x = 0; x < sconge.length; x++) {
if (x == sconge.length-1) {
display.push(Math.floor(((Date.parse(today) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)))
} else {
display.push((new Date(fconge[x].toString().slice(3,5)+'/'+fconge[x].toString().slice(0,2)+'/'+fconge[x].toString().slice(6,10)) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)
}
}
for (y = 0; y < display.length; y++) {
congelamento = Number(congelamento) + Number(display[y])
}
return Math.ceil(congelamento)
} else if (startcongelamento.length > 10) {
Logger.log('desigual, só start > 10')
var display = []
for (x = 0; x < sconge.length; x++) {
if (x == sconge.length-1) {
display.push(Math.floor(((Date.parse(today) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)))
} else {
display.push((new Date(fconge) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7)
}
}
for (y = 0; y < display.length; y++) {
congelamento = Number(congelamento) + Number(display[y])
}
return Math.ceil(congelamento)
} else {
Logger.log('desigual, nenhum > 10')
congelamento = Math.floor(((Date.parse(today) - new Date(sconge))/8.64E7))
return Math.ceil(congelamento)
}
} else {
if (startcongelamento.length > 10) {
Logger.log('igual, start e final > 10')
for (x = 0; x < sconge.length; x++) {
congelamento = congelamento + (new Date(fconge[x].toString().slice(3,5)+'/'+fconge[x].toString().slice(0,2)+'/'+fconge[x].toString().slice(6,10)) - new Date(sconge[x].toString().slice(3,5)+'/'+sconge[x].toString().slice(0,2)+'/'+sconge[x].toString().slice(6,10)))/8.64E7
}
} else {
Logger.log('igual, nenhum > 10')
congelamento = (new Date(fconge) - new Date(sconge))/8.64E7
}
}
//declinio
if (startdeclinio == null || startdeclinio == undefined || startdeclinio == ''){
} else {
if (startdeclinio.length > 10) {
Logger.log('declinio, >10')
for (y = 0; y < sdec.length; y++) {
declinio = declinio + (new Date(fdec[y].toString().slice(3,5)+'/'+fdec[y].toString().slice(0,2)+'/'+fdec[y].toString().slice(6,10)) - new Date(sdec[y].toString().slice(3,5)+'/'+sdec[y].toString().slice(0,2)+'/'+sdec[y].toString().slice(6,10)))/8.64E7
}
} else {
Logger.log('declinio, <10')
declinio = (new Date(fdec) - new Date(sdec))/8.64E7
}
}
if (start.length > 10) {
var nstart = start.toString().slice(start.toString().lastIndexOf('#')+2, start.length)
if(cancelamento != null && cancelamento != '') {
return ((((new Date(cancelamento) - new Date(nstart.toString().slice(3,5)+'/'+nstart.toString().slice(0,2)+'/'+nstart.toString().slice(6,10)))/8.64E7 - congelamento) - declinio))
} else if(end != null && end != '') {
return ((((new Date(end) - new Date(nstart.toString().slice(3,5)+'/'+nstart.toString().slice(0,2)+'/'+nstart.toString().slice(6,10)))/8.64E7 - congelamento) - declinio))
} else {
return ((Math.floor((Date.parse(today) - new Date(nstart.toString().slice(3,5)+'/'+nstart.toString().slice(0,2)+'/'+nstart.toString().slice(6,10)))/8.64E7) - congelamento) - declinio)
}
} else {
var nstart = start
if(cancelamento != null && cancelamento != '') {
return ((((new Date(cancelamento) - new Date(start))/8.64E7 - congelamento) - declinio))
} else if(end != null && end != '') {
return ((((new Date(end) - new Date(start))/8.64E7 - congelamento) - declinio))
} else {
return ((Math.floor((Date.parse(today) - new Date(start))/8.64E7) - congelamento) - declinio)
}
}
}
}
So, I got what I was doing wrong. Thanks evolutionxbox, btw, because you sparked my creativity.
I was not actually calling the methods. When the syntax was changed, the code worked.
Don't know if it was a fluke on my part, or if the autocomplete parameters changed, but, regardless, yes, methods must be called and parameters mustn't. :P

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

How to make this floating menu work only when specific #divs become visible?

I needed to make a floating menu, I searched online and found a script here http://www.jtricks.com/javascript/navigation/floating.html
/* Script by: www.jtricks.com
* Version: 1.12 (20120823)
* Latest version: www.jtricks.com/javascript/navigation/floating.html
*
* License:
* GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*/
var floatingMenu =
{
hasInner: typeof(window.innerWidth) == 'number',
hasElement: typeof(document.documentElement) == 'object'
&& typeof(document.documentElement.clientWidth) == 'number'};
var floatingArray =
[
];
floatingMenu.add = function(obj, options)
{
var name;
var menu;
if (typeof(obj) === "string")
name = obj;
else
menu = obj;
if (options == undefined)
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: 0,
targetTop: 0,
distance: .07,
snap: true,
updateParentHeight: false
});
}
else
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: options.targetLeft,
targetRight: options.targetRight,
targetTop: options.targetTop,
targetBottom: options.targetBottom,
centerX: options.centerX,
centerY: options.centerY,
prohibitXMovement: options.prohibitXMovement,
prohibitYMovement: options.prohibitYMovement,
distance: options.distance != undefined ? options.distance : .07,
snap: options.snap,
ignoreParentDimensions: options.ignoreParentDimensions,
updateParentHeight:
options.updateParentHeight == undefined
? false
: options.updateParentHeight,
scrollContainer: options.scrollContainer,
scrollContainerId: options.scrollContainerId,
confinementArea: options.confinementArea,
confinementAreaId:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '#'
? options.confinementArea.substring(1)
: undefined,
confinementAreaClassRegexp:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '.'
? new RegExp("(^|\\s)" + options.confinementArea.substring(1) + "(\\s|$)")
: undefined
});
}
};
floatingMenu.findSingle = function(item)
{
if (item.id)
item.menu = document.getElementById(item.id);
if (item.scrollContainerId)
item.scrollContainer = document.getElementById(item.scrollContainerId);
};
floatingMenu.move = function (item)
{
if (!item.prohibitXMovement)
{
item.menu.style.left = item.nextX + 'px';
item.menu.style.right = '';
}
if (!item.prohibitYMovement)
{
item.menu.style.top = item.nextY + 'px';
item.menu.style.bottom = '';
}
};
floatingMenu.scrollLeft = function(item)
{
// If floating within scrollable container use it's scrollLeft
if (item.scrollContainer)
return item.scrollContainer.scrollLeft;
var w = window.top;
return this.hasInner
? w.pageXOffset
: this.hasElement
? w.document.documentElement.scrollLeft
: w.document.body.scrollLeft;
};
floatingMenu.scrollTop = function(item)
{
// If floating within scrollable container use it's scrollTop
if (item.scrollContainer)
return item.scrollContainer.scrollTop;
var w = window.top;
return this.hasInner
? w.pageYOffset
: this.hasElement
? w.document.documentElement.scrollTop
: w.document.body.scrollTop;
};
floatingMenu.windowWidth = function()
{
return this.hasElement
? document.documentElement.clientWidth
: document.body.clientWidth;
};
floatingMenu.windowHeight = function()
{
if (floatingMenu.hasElement && floatingMenu.hasInner)
{
// Handle Opera 8 problems
return document.documentElement.clientHeight > window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
}
else
{
return floatingMenu.hasElement
? document.documentElement.clientHeight
: document.body.clientHeight;
}
};
floatingMenu.documentHeight = function()
{
var innerHeight = this.hasInner
? window.innerHeight
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
innerHeight);
};
floatingMenu.documentWidth = function()
{
var innerWidth = this.hasInner
? window.innerWidth
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollWidth,
body.offsetWidth,
html.clientWidth,
html.scrollWidth,
html.offsetWidth,
innerWidth);
};
floatingMenu.calculateCornerX = function(item)
{
var offsetWidth = item.menu.offsetWidth;
var result = this.scrollLeft(item) - item.parentLeft;
if (item.centerX)
{
result += (this.windowWidth() - offsetWidth)/2;
}
else if (item.targetLeft == undefined)
{
result += this.windowWidth() - item.targetRight - offsetWidth;
}
else
{
result += item.targetLeft;
}
if (document.body != item.menu.parentNode
&& result + offsetWidth >= item.confinedWidthReserve)
{
result = item.confinedWidthReserve - offsetWidth;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.calculateCornerY = function(item)
{
var offsetHeight = item.menu.offsetHeight;
var result = this.scrollTop(item) - item.parentTop;
if (item.centerY)
{
result += (this.windowHeight() - offsetHeight)/2;
}
else if (item.targetTop === undefined)
{
result += this.windowHeight() - item.targetBottom - offsetHeight;
}
else
{
result += item.targetTop;
}
if (document.body != item.menu.parentNode
&& result + offsetHeight >= item.confinedHeightReserve)
{
result = item.confinedHeightReserve - offsetHeight;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.isConfinementArea = function(item, area)
{
return item.confinementAreaId != undefined
&& area.id == item.confinementAreaId
|| item.confinementAreaClassRegexp != undefined
&& area.className
&& item.confinementAreaClassRegexp.test(area.className);
};
floatingMenu.computeParent = function(item)
{
if (item.ignoreParentDimensions)
{
item.confinedHeightReserve = this.documentHeight();
item.confinedWidthReserver = this.documentWidth();
item.parentLeft = 0;
item.parentTop = 0;
return;
}
var parentNode = item.menu.parentNode;
var parentOffsets = this.offsets(parentNode, item);
item.parentLeft = parentOffsets.left;
item.parentTop = parentOffsets.top;
item.confinedWidthReserve = parentNode.clientWidth;
// We could have absolutely-positioned DIV wrapped
// inside relatively-positioned. Then parent might not
// have any height. Try to find parent that has
// and try to find whats left of its height for us.
var obj = parentNode;
var objOffsets = this.offsets(obj, item);
if (item.confinementArea == undefined)
{
while (obj.clientHeight + objOffsets.top
< item.menu.scrollHeight + parentOffsets.top
|| item.menu.parentNode == obj
&& item.updateParentHeight
&& obj.clientHeight + objOffsets.top
== item.menu.scrollHeight + parentOffsets.top)
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
else
{
while (obj.parentNode != undefined
&& !this.isConfinementArea(item, obj))
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
item.confinedHeightReserve = obj.clientHeight
- (parentOffsets.top - objOffsets.top);
};
floatingMenu.offsets = function(obj, item)
{
var result =
{
left: 0,
top: 0
};
if (obj === item.scrollContainer)
return;
while (obj.offsetParent && obj.offsetParent != item.scrollContainer)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
if (window == window.top)
return result;
// we're IFRAMEd
var iframes = window.top.document.body.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++)
{
if (iframes[i].contentWindow != window)
continue;
obj = iframes[i];
while (obj.offsetParent)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
}
return result;
};
floatingMenu.doFloatSingle = function(item)
{
this.findSingle(item);
if (item.updateParentHeight)
{
item.menu.parentNode.style.minHeight =
item.menu.scrollHeight + 'px';
}
var stepX, stepY;
this.computeParent(item);
var cornerX = this.calculateCornerX(item);
var stepX = (cornerX - item.nextX) * item.distance;
if (Math.abs(stepX) < .5 && item.snap
|| Math.abs(cornerX - item.nextX) <= 1)
{
stepX = cornerX - item.nextX;
}
var cornerY = this.calculateCornerY(item);
var stepY = (cornerY - item.nextY) * item.distance;
if (Math.abs(stepY) < .5 && item.snap
|| Math.abs(cornerY - item.nextY) <= 1)
{
stepY = cornerY - item.nextY;
}
if (Math.abs(stepX) > 0 ||
Math.abs(stepY) > 0)
{
item.nextX += stepX;
item.nextY += stepY;
this.move(item);
}
};
floatingMenu.fixTargets = function()
{
};
floatingMenu.fixTarget = function(item)
{
};
floatingMenu.doFloat = function()
{
this.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
this.fixTarget(floatingArray[i]);
this.doFloatSingle(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 20);
};
floatingMenu.insertEvent = function(element, event, handler)
{
// W3C
if (element.addEventListener != undefined)
{
element.addEventListener(event, handler, false);
return;
}
var listener = 'on' + event;
// MS
if (element.attachEvent != undefined)
{
element.attachEvent(listener, handler);
return;
}
// Fallback
var oldHandler = element[listener];
element[listener] = function (e)
{
e = (e) ? e : window.event;
var result = handler(e);
return (oldHandler != undefined)
&& (oldHandler(e) == true)
&& (result == true);
};
};
floatingMenu.init = function()
{
floatingMenu.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
floatingMenu.initSingleMenu(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 100);
};
// Some browsers init scrollbars only after
// full document load.
floatingMenu.initSingleMenu = function(item)
{
this.findSingle(item);
this.computeParent(item);
this.fixTarget(item);
item.nextX = this.calculateCornerX(item);
item.nextY = this.calculateCornerY(item);
this.move(item);
};
floatingMenu.insertEvent(window, 'load', floatingMenu.init);
// Register ourselves as jQuery plugin if jQuery is present
if (typeof(jQuery) !== 'undefined')
{
(function ($)
{
$.fn.addFloating = function(options)
{
return this.each(function()
{
floatingMenu.add(this, options);
});
};
}) (jQuery);
}
The script requires the menu to have #floatdiv id. I made my div, #floatdiv, and added the following line of javascript to the head to make the action start working:
<script type="text/javascript">
floatingMenu.add('floatdiv',
{
targetLeft: 250,
targetTop: 290,
snap: true
});
</script>
the #floatdiv css is here,
#floatdiv{
height:45px;
width:830px;
z-index:2;
}
The script is working fine. When I scroll down, the menu float as specified. But I dun wanna the menu to float all the way with scrolling. I need the float of the menu to fire only when I enter specific divs not all the way with scrolling.. Any clues?
is this what look like?
html
<div id="header">HEADER</div>
<div id="content">
<div id="left">LEFT</div>
<div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>
js
$(function() {
var $sidebar = $("#right"),
$window = $(window),
rightOffset = $sidebar.offset(),
rightDelta = $("#footer").offset().top - $("#header").offset().top - $("#header").outerHeight() - $("#right").outerHeight(),
topPadding = 15;
$window.scroll(function() {
$sidebar.stop().animate({
marginTop: Math.max(Math.min($window.scrollTop() - rightOffset.top + topPadding, rightDelta), 0)
});
});
});
working demo
hope this help you
I wrote the script listed in the question.
The script is very versatile and can make div float within a specific area (e.g. another container div). Here are the instructions:
http://www.jtricks.com/javascript/navigation/floating/confined_demo.html

I want to add Mouseover effect on my Canvas using JavaScript

Mouseover effect should be created only on specific canvas location.
In addition I've created the MousePosition function(See below).
commands for Mouseover effect should be on the MouseOverButton function.
But still It can't seems to work.
My code:
function init() {
var can=document.getElementById("SnakeCanvas");
var ctx=can.getContext("2d");
can.addEventListener('mouseover',MouseOverButton, false);
}
function getPosition(event) {
var x = new Number();
var y = new Number();
var can = document.getElementById("SnakeCanvas");
if (event.x != undefined && event.y != undefined) {
x = event.x;
y = event.y;
} else {//Firefox Compatability//
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= can.offsetLeft;
y -= can.offsetTop;
return {mx:x, my:y};
}
function MouseOverButton(e) {
var can=document.getElementById("SnakeCanvas");
var ctx=can.getContext("2d");
var cell=getPosition(event);
if ((cell.mx > 854 && cell.mx < 985) && (cell.my > 256 && cell.my < 315)) {
ReplaceImage(ctx,'Images/New_Game_Hover.png',570,100,140,70);
}
}
Your event parameter in function MouseOverButton(e) is called e but you use event when passing it to getPosition:
var cell=getPosition(event); should be var cell=getPosition(e);
Try this:
function MouseOverButton(e) {
e = e || window.event; // Compatibility
var can = document.getElementById("SnakeCanvas");
var ctx = can.getContext("2d");
var cell = getPosition(e);
// ^ That was `event`, breaking your code.
if ((cell.mx > 854 && cell.mx < 985) && (cell.my > 256 && cell.my < 315)) {
ReplaceImage(ctx,'Images/New_Game_Hover.png',570,100,140,70);
}
}

Trying to find javascript element's position on screen....Not working properly on webkit browsers

This is the code i'm using right now. On webkit browsers (Chrome and Safari Specifically) if the page is scrolled, it doesn't take into account the amount that page has been scrolled. I need help redesigning the function to work for Webkit browsers. And I don't want to be loading up jQuery as this will be used on a web widget and I need to keep the file size down. Thanks guys!
function __getIEVersion() {
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function __getOperaVersion() {
var rv = 0; // Default value
if (window.opera) {
var sver = window.opera.version();
rv = parseFloat(sver);
}
return rv;
}
var __userAgent = navigator.userAgent;
var __isIE = navigator.appVersion.match(/MSIE/) != null;
var __IEVersion = __getIEVersion();
var __isIENew = __isIE && __IEVersion >= 8;
var __isIEOld = __isIE && !__isIENew;
var __isFireFox = __userAgent.match(/firefox/i) != null;
var __isFireFoxOld = __isFireFox && ((__userAgent.match(/firefox\/2./i) != null) ||
(__userAgent.match(/firefox\/1./i) != null));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;
var __isWebKit = navigator.appVersion.match(/WebKit/) != null;
var __isChrome = navigator.appVersion.match(/Chrome/) != null;
var __isOpera = window.opera != null;
var __operaVersion = __getOperaVersion();
var __isOperaOld = __isOpera && (__operaVersion < 10);
function __parseBorderWidth(width) {
var res = 0;
if (typeof(width) == "string" && width != null && width != "" ) {
var p = width.indexOf("px");
if (p >= 0) {
res = parseInt(width.substring(0, p));
}
else {
//do not know how to calculate other values
//(such as 0.5em or 0.1cm) correctly now
//so just set the width to 1 pixel
res = 1;
}
}
return res;
}
//returns border width for some element
function __getBorderWidth(element) {
var res = new Object();
res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
if (window.getComputedStyle) {
//for Firefox
var elStyle = window.getComputedStyle(element, null);
res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));
res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));
res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));
res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));
}
else {
//for other browsers
res.left = __parseBorderWidth(element.style.borderLeftWidth);
res.top = __parseBorderWidth(element.style.borderTopWidth);
res.right = __parseBorderWidth(element.style.borderRightWidth);
res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
}
return res;
}
//returns the absolute position of some element within document
function getElementAbsolutePos(element) {
var res = new Object();
res.x = 0; res.y = 0;
if (element !== null) {
if (element.getBoundingClientRect) {
var viewportElement = document.documentElement;
var box = element.getBoundingClientRect();
var scrollLeft = viewportElement.scrollLeft;
var scrollTop = viewportElement.scrollTop;
res.x = box.left + scrollLeft;
res.y = box.top + scrollTop;
}
else { //for old browsers
res.x = element.offsetLeft;
res.y = element.offsetTop;
var parentNode = element.parentNode;
var borderWidth = null;
while (offsetParent != null) {
res.x += offsetParent.offsetLeft;
res.y += offsetParent.offsetTop;
var parentTagName =
offsetParent.tagName.toLowerCase();
if ((__isIEOld && parentTagName != "table") ||
((__isFireFoxNew || __isChrome) &&
parentTagName == "td")) {
borderWidth = kGetBorderWidth
(offsetParent);
res.x += borderWidth.left;
res.y += borderWidth.top;
}
if (offsetParent != document.body &&
offsetParent != document.documentElement) {
res.x -= offsetParent.scrollLeft;
res.y -= offsetParent.scrollTop;
}
//next lines are necessary to fix the problem
//with offsetParent
if (!__isIE && !__isOperaOld || __isIENew) {
while (offsetParent != parentNode &&
parentNode !== null) {
res.x -= parentNode.scrollLeft;
res.y -= parentNode.scrollTop;
if (__isFireFoxOld || __isWebKit)
{
borderWidth =
kGetBorderWidth(parentNode);
res.x += borderWidth.left;
res.y += borderWidth.top;
}
parentNode = parentNode.parentNode;
}
}
parentNode = offsetParent.parentNode;
offsetParent = offsetParent.offsetParent;
}
}
}
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 res;
}
if (element.getBoundingClientRect) {
var viewportElement = document.documentElement;
var box = element.getBoundingClientRect();
var scrollLeft = viewportElement.scrollLeft;
var scrollTop = viewportElement.scrollTop;
res.x = box.left + scrollLeft;
res.y = box.top + scrollTop;
}
I'm concerned that this code block only uses one way of attempting to detect the scroll position. I would move the bottom block of code to the top of the function and use scrOfX/Y instead of scrollLeft and scrollTop.

Categories

Resources