Need to position a div based on the href element position in the page.
The code which I currentl have works on my machine which runs IE8.
The same code does not work on another machine with same configuration . Please help
BTW , the div is absolutely position and in the javascript we have:
divobj.style.left = event.x - 185;
divobj.style.top = event.y - 5;
try to use this function.
function getElementPosition(element) {
var x = 0; var y = 0;
while(element !=null ) {
x += element.offsetLeft || 0;
y += element.offsetTop || 0;
element = element.offsetParent;
if (!element || element.style['position'] == 'relative' || element.tagName == 'BODY') break;
}
return {'x':x, 'y':y};
}
it will retrun the position of your link element, but you have to pass that element as argument to this function.
The solution might be as simple as adding a unit of measurement, e.g.:
divobj.style.left = event.x - 185 + 'px'; divobj.style.top = event.y - 5 + 'px';
Some browsers assume 'px' as the unit of measurement; others don't make an assumption and therefore do nothing with what they consider an invalid value.
Related
Within my project I have a character that automatically walks down the screen. I want to detect whenever the character hits a certain dungeon (each "dungeon" is a div with some text inside).
Here is my code in a simplified format:
//call the function
console.log(isCollide(characterData[0][0], document.getElementsByClassName("Dungeon_Wrapper_Room")[a])));
var isCollide = function(a, b) {
//Used to parse get the x/y pixel coordinates by removing the "px" at the end of the string.
var aTOPstr = a.style.top;
var aTOP = (parseInt(aTOPstr.slice(0, aTOPstr.length-2)));
var aLEFTstr = a.style.left;
var aLEFT = (parseInt(aLEFTstr.slice(0, aLEFTstr.length-2)));
var bTOPstr = b.style.top;
var bTOP = (parseInt(bTOPstr.slice(0, bTOPstr.length-2)));
var bLEFTstr = b.style.left;
var bLEFT = (parseInt(bLEFTstr.slice(0, bLEFTstr.length-2)));
console.log(((aTOP + 32) > (bTOP))+" "+(aTOP < (bTOP - 32))+" "+((aLEFT + 32) > bLEFT)+" "+(aLEFT < (bLEFT + 50)));
return (
!((aTOP + 32) < (bTOP)) ||
(aTOP > (bTOP + 50)) ||
((aLEFT + 32) < aLEFT) ||
(aLEFT > (aLEFT + 50))
);
};
The character image was created dynamically (in the end I'll use a for loop to run through an array of characters, each with this detection).
var characterData = [
[document.createElement("img"), {/*Misc. Character Data Goes Here*/}]
];
characterData[0][0].src = "images/characters/default.png";
characterData[0][0].style.position = "relative";
characterData[0][0].style.left += ((50-32)/2)+"px";
characterData[0][0].style.top += (-(50-32+25))+"px";
characterData[0][0].id = "character0";
tavernBox.appendChild(characterData[0][0]);
My HTML:
<div id="Town_Wrapper">
<div id="townBoxWrapper">
<div id="tavernBox">
<!-- Characters are appended here -->
</div>
</div>
</div>
<div id="Dungeon_Wrapper">
<div class='Dungeon_Wrapper_Room'>Boss
<!--Box character is being detected with-->
</div>
</div>
I've based my hit detection off the answer I found here: https://stackoverflow.com/a/7301852/7214959 but still am having no success.
I have absolutely no clue what is wrong with it. I've tried switching the < around and other functions but still can't find anything. I've also tried going from relative to absolute positioning and still got nothing. The isCollide function needs to return true or !false to indicate it has collided but each section of the if statement always returns "false" and there is never a single "true".
JSFiddle (contains debugging for console and alert): https://jsfiddle.net/drfyvLng/
Solved: The selected answer solves the issue presented in the jsfiddle. Within my own code I had to turn the certain dungeon into absolute positioning and find its location use .offsetTOP and .offsetLEFT. Additionally I made the return formula detect when the character is inside the box rather than when it isn't.
There were a few issues with the JSfiddle.
This was evaluating to null because there's no top set in the css style.
var bTOPstr = b.style.top;
Update your CSS to this and that part is covered.
<div class='Dungeon_Wrapper_Room' style="background-color: yellow; min-height:50px; top:0px; bottom:50px; left:0px; right:100px">
Then your if statement that checks collision is different to the one you based it off, be careful when copying code!
!((aTOP + 32) < (bTOP)) ||
(aTOP > (bTOP + 50)) ||
((aLEFT + 32) < aLEFT) ||
(aLEFT > (aLEFT + 50))
aLeft + 32 < aLeft should be aLeft + 32 < bLeft
aLeft > aLeft + 50 should be aLeft > bLeft + 50
Finally, you need another bracket on the if statement. The answer your based it off is checking '!' on the entire expression, yours just uses the first line.
So now it looks like this.
!(((aTOP + 32) < (bTOP)) ||
(aTOP > (bTOP + 50)) ||
((aLEFT + 32) < bLEFT) ||
(aLEFT > (bLEFT + 50)))
Which should work.
I can't get my head around this problem, so i hope that you guys can help me fixing it.
The thing is that I want to check if an div is overlapping an another div when they are dynamically added to the body.
Let's say that I've got an first div with the following information:
X1 = 316, X2 = 440
This is being calculated with the information that an box has an length of 60px and 1px margin around him. Also, the exL stands for the amount of 'boxes' inside the div ( in this test case it's 2, but it will be many more... ) So the code to calculate that is:
var X2 = ( oldX1 + ( kist_length * exL ) + ( 2 * exL))
I've got this code so far:
// X:
oldX1 = ( 316 );
oldX2 = ( oldX1 + ( kist_length * exL ) + ( 2 * exL));
newX1 = ( 99 );
newX2 = ( newX1 + ( kist_length * newLength ) + ( 2 * newLength));
if( (newX1 >= oldX1 || newX1 <= oldX2) || ( newX2 >= oldX2 || newX2 <= oldX2) ){
console.log("X is overlapping...");
}
If i use the code above the program says it's overlapping, but as you can see below, that's not true. the values that the checker is using are ( + kisten stands for + the length ( so the boxes + length of box * times of boxes ):
newX = 99
newX + kisten = 223
oldX = 316
oldX + kisten = 440
I know that it's because the OR statement. But if I use AND statements between the () inside the if, it's not working 100% to. Let's take a look at the following picture:
First I've placed Box1. After that I've placed Box2, that succeeded without the warning about an overlapping. But X is overlapping...( not the Y, but the X is... ). When i place Box3, i do get the warning that X is overlapping...
So my question is rather simple ( but i guess the answer isn't... ), What do I wrong with the check? Which part of the if statement did i do wrong?
I guess there is a typo in your script, since newX2 >= oldX2 || newX2 <= oldX2 is always true :-)
But the condition in order to not have any overlapping is that (I reason on segments since you are dealing axis by axis here) new segment is before the old one :
newX1----------------newX2 oldX1---------------oldX2
or the second one is after first one :
oldX1---------------oldX2 newX1----------------newX2
So the corresponding condition is the following one :
function overlaps() {
var minOldX = Math.min(oldX1, newX1),
maxOldX = Math.max(oldX1, newX1),
minNewX = Math.min(oldX2, newX2),
maxNewX = Math.max(oldX2, newX2);
return (
maxNewX <= minOldX || // <- first case
minNewX >= maxOldX // <- second case
);
}
I'm looking for a function that would get an element from the DOM and determine whether it is in the sight of the user vertically?
I searched for a function that would get an element and check if it is in the current scroll height the user is viewing. I ended up trying a bunch of functions that didn't quite do what I needed and I built my own. Since I didn't find such function I'm now sharing it with you guys in case someone needs it in future! :P This is without using any frameworks or plugins.
function visible(a, t){
// a => element
// t => tolerance, how much pixels can be hidden and still return true
var w_top = window.pageYOffset || document.documentElement.scrollTop,
w_hgh = window.outerHeight,
a_top = 0,
a_hgh = a.offsetHeight;
while(a.tagName.toLowerCase() !== 'body') {
a_top += a.offsetTop;
a = a.offsetParent;
}
var b = (w_top + w_hgh) - (a_top + a_hgh);
if(b > (0 - t) && b < (w_hgh - a_hgh + t)){
return true;
}
return false;
}
An example in use:
var element = document.getElementById('id');
if(!visible(element, 50)){
element.focus();
}
I am using jquery.event.drag.js in a project I am creating, and I am trying to figure out a way to run a script for every X amount of pixels I have dragged. I am using only the X axis for this. Here is some code I have right now.
$('body').drag(function( ev, dd ){
var newcell = currentCell;
var dragOffset = Math.floor(dd.offsetX / 100);
if (dragOffset >= 1) {
alert("Dragged 100px");
}
newcell += dragOffset;
$('#info').html(dragOffset + " | " + dd.offsetX);
updateStack(newcell, magnifyMode);
});
This works, however, since this script runs for every pixel dragged, this runs the alert after 100px dragged, but from then on it runs for every pixel I drag it after that. I'm looking for a way to only run it for every 100px I drag it. Any ideas?
have an outside variable tracking when you last did the alert:
var chunkedOffset = 0;
$('body').drag(function( ev, dd ){
var newcell = currentCell;
var dragOffset = dd.offsetX / 100;
if (dragOffset > chunkedOffset) {
chunkedOffset = dragOffset;
alert("Dragged 100px");
}
newcell += dragOffset;
$('#info').html(dragOffset + " | " + dd.offsetX);
updateStack(newcell, magnifyMode);
});
I'm not entirely familiar with drag.js, but, you could just use modulus division to make sure its every 100px.
x % 100 - will be 0 if divisible by 100, so
if(dd.offsetX % 100 == 0)
{
alert("Dragged 100px");
}
I have the following JS fee calculator on a web site:
http://jsfiddle.net/billsinc/HMFYK/
function updateOutput() {
//get form
var form = document.getElementById('calc');
var x = form.elements['x'].value;
x = x.replace(/,/g, "");
// determine multiplier
if (x > 11111 && x < 83333) {
y = 0.009;
}
if (x >= 83333 && x < 166667) {
y = 0.007;
}
if (x >= 166667 && x < 250000) {
y = 0.006;
}
if (x >= 250000) {
y = 0.005;
}
// add data addon
if (form.elements['pd'].checked === true) {
p = 250;
}
else {
p = 0;
}
// calculate monthly price
if (x > 11111) {
form.elements['z'].value = Math.round(eval(parseInt(x, 10) * y + p));
}
else {
form.elements['z'].value = Math.round(eval(100 + p));
}
}
If you enter "12000" (or some number greater than 11,111) it will properly calculate in FF, Chrome and Safari.
I've been unable to get it to work in IE. It throws the following error after entering a value:
SCRIPT5007: Unable to set value of the property 'value': object is null or undefined
I've seen this error a number of times on SO but all the resolutions are related .Net or some issue with embedding Flash.
Any help would be appreciated...thanks in advance!
It appears that IE does not include <output> elements in the form.elements collection, so form.elements['z'] is undefined in IE. (If you click the link, you'll see that <output> is not supported until IE10.) Other browsers do include <output>s in their elements collections.
Either make z into a read-only <input>, or give your <output> an id and get it with document.getElementById.