Finding closest anchor href via scrollOffset - javascript

I have a UIWebView with an HTML page completely loaded. The UIWebView has a frame of 320 x 480 and scrolls horizontally. I can get the current offset a user is currently at. I would like to find the closest anchor using the XY offset so I can "jump to" that anchors position. Is this at all possible? Can someone point me to a resource in Javascript for doing this?
<a id="p-1">Text Text Text Text Text Text Text Text Text<a id="p-2">Text Text Text Text Text Text Text Text Text ...
Update
My super sad JS code:
function posForElement(e)
{
var totalOffsetY = 0;
do
{
totalOffsetY += e.offsetTop;
} while(e = e.offsetParent)
return totalOffsetY;
}
function getClosestAnchor(locationX, locationY)
{
var a = document.getElementsByTagName('a');
var currentAnchor;
for (var idx = 0; idx < a.length; ++idx)
{
if(a[idx].getAttribute('id') && a[idx+1])
{
if(posForElement(a[idx]) <= locationX && locationX <= posForElement(a[idx+1]))
{
currentAnchor = a[idx];
break;
}
else
{
currentAnchor = a[0];
}
}
}
return currentAnchor.getAttribute('id');
}
Objective-C
float pageOffset = 320.0f;
NSString *path = [[NSBundle mainBundle] pathForResource:#"GetAnchorPos" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:jsCode];
NSString *execute = [NSString stringWithFormat:#"getClosestAnchor('%f', '0')", pageOffset];
NSString *anchorID = [webView stringByEvaluatingJavaScriptFromString:execute];

[UPDATE] I rewrote the code to match all the anchors that have an id, and simplified the comparison of the norm of the vectors in my sortByDistance function.
Check my attempt on jsFiddle (the previous one was here ).
The javascript part :
// findPos : courtesy of #ppk - see http://www.quirksmode.org/js/findpos.html
var findPos = function(obj) {
var curleft = 0,
curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while ((obj = obj.offsetParent)) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return [curleft, curtop];
};
var findClosestAnchor = function (anchors) {
var sortByDistance = function(element1, element2) {
var pos1 = findPos( element1 ),
pos2 = findPos( element2 );
// vect1 & vect2 represent 2d vectors going from the top left extremity of each element to the point positionned at the scrolled offset of the window
var vect1 = [
window.scrollX - pos1[0],
window.scrollY - pos1[1]
],
vect2 = [
window.scrollX - pos2[0],
window.scrollY - pos2[1]
];
// we compare the length of the vectors using only the sum of their components squared
// no need to find the magnitude of each (this was inspired by Mageek’s answer)
var sqDist1 = vect1[0] * vect1[0] + vect1[1] * vect1[1],
sqDist2 = vect2[0] * vect2[0] + vect2[1] * vect2[1];
if ( sqDist1 < sqDist2 ) return -1;
else if ( sqDist1 > sqDist2 ) return 1;
else return 0;
};
// Convert the nodelist to an array, then returns the first item of the elements sorted by distance
return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];
};
You can retrieve and cache the anchors like so when the dom is ready : var anchors = document.body.querySelectorAll('a[id]');
I’ve not tested it on a smartphone yet but I don’t see any reasons why it wouldn’t work.
Here is why I used the var foo = function() {}; form (more javascript patterns).
The return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0]; line is actually a bit tricky.
document.body.querySelectorAll('a['id']') returns me a NodeList with all the anchors that have the attribute "id" in the body of the current page.
Sadly, a NodeList object does not have a "sort" method, and it is not possible to use the sort method of the Array prototype, as it is with some other methods, such as filter or map (NodeList.prototype.sort = Array.prototype.sort would have been really nice).
This article explains better that I could why I used Array.prototype.slice.call to turn my NodeList into an array.
And finally, I used the Array.prototype.sort method (along with a custom sortByDistance function) to compare each element of the NodeList with each other, and I only return the first item, which is the closest one.
To find the position of the elements that use fixed positionning, it is possible to use this updated version of findPos : http://www.greywyvern.com/?post=331.
My answer may not be the more efficient (drdigit’s must be more than mine) but I preferred simplicity over efficiency, and I think it’s the easiest one to maintain.
[YET ANOTHER UPDATE]
Here is a heavily modified version of findPos that works with webkit css columns (with no gaps):
// Also adapted from PPK - this guy is everywhere ! - check http://www.quirksmode.org/dom/getstyles.html
var getStyle = function(el,styleProp)
{
if (el.currentStyle)
var y = el.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
return y;
}
// findPos : original by #ppk - see http://www.quirksmode.org/js/findpos.html
// made recursive and transformed to returns the corect position when css columns are used
var findPos = function( obj, childCoords ) {
if ( typeof childCoords == 'undefined' ) {
childCoords = [0, 0];
}
var parentColumnWidth,
parentHeight;
var curleft, curtop;
if( obj.offsetParent && ( parentColumnWidth = parseInt( getStyle( obj.offsetParent, '-webkit-column-width' ) ) ) ) {
parentHeight = parseInt( getStyle( obj.offsetParent, 'height' ) );
curtop = obj.offsetTop;
column = Math.ceil( curtop / parentHeight );
curleft = ( ( column - 1 ) * parentColumnWidth ) + ( obj.offsetLeft % parentColumnWidth );
curtop %= parentHeight;
}
else {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
}
curleft += childCoords[0];
curtop += childCoords[1];
if( obj.offsetParent ) {
var coords = findPos( obj.offsetParent, [curleft, curtop] );
curleft = coords[0];
curtop = coords[1];
}
return [curleft, curtop];
}

I found a way to make it, without using scrollOffset. It's a bit complicated so if you have any question to understand it just comment.
HTML :
<body>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<a />Text Text Text Text Text Text Text Text Text
<br /><br /><br /><br /><br />
<a />Text Text Text Text Text Text Text Text Text
</body>
CSS :
body
{
height:3000px;
}
JS :
var tempY;
function getClosestAnchor(e)
{
if((window.event?event.keyCode:e.which)!=97)return;
var allAnchors=document.getElementsByTagName("a");
var allDiff=[];
for(var a=0;a<allAnchors.length;a++)allDiff[a]=margeY(allAnchors[a])-tempY;
var smallest=allDiff[0];
for(var a=1;a<allDiff.length;a++)
{
if(Math.abs(smallest)>Math.abs(allDiff[a]))
{
smallest=allDiff[a];
}
}
window.scrollBy(0,smallest);
}
function margeY(obj)
{
var posY=0;
if(!obj.offsetParent)return;
do posY+=obj.offsetTop;
while(obj=obj.offsetParent);
return posY;
}
function update(e)
{
if(e.pageY)tempY=e.pageY;
else tempY=e.clientY+(document.documentElement.scrollTop||document.body.scrollTop)-document.documentElement.clientTop;
}
window.onkeypress=getClosestAnchor;
window.onmousemove=update;
Here is a fiddle demonstration : http://jsfiddle.net/jswuC/
Bonus : You don't have to specify an id to all the anchors.

Phew! I finished!
JS :
var x=0,y=0;//Here are the given X and Y, you can change them
var idClosest;//Id of the nearest anchor
var smallestIndex;
var couplesXY=[];
var allAnchors;
var html=document.getElementsByTagName("html")[0];
html.style.width="3000px";//You can change 3000, it's to make the possibility of horizontal scroll
html.style.height="3000px";//Here too
function random(min,max)
{
var nb=min+(max+1-min)*Math.random();
return Math.floor(nb);
}
function left(obj)//A remixed function of this site http://www.quirksmode.org/js/findpos.html
{
if(obj.style.position=="absolute")return parseInt(obj.style.left);
var posX=0;
if(!obj.offsetParent)return;
do posX+=obj.offsetLeft;
while(obj=obj.offsetParent);
return posX;
}
function top(obj)
{
if(obj.style.position=="absolute")return parseInt(obj.style.top);
var posY=0;
if(!obj.offsetParent)return;
do posY+=obj.offsetTop;
while(obj=obj.offsetParent);
return posY;
}
function generateRandomAnchors()//Just for the exemple, you can delete the function if you have already anchors
{
for(var a=0;a<50;a++)//You can change 50
{
var anchor=document.createElement("a");
anchor.style.position="absolute";
anchor.style.width=random(0,100)+"px";//You can change 100
anchor.style.height=random(0,100)+"px";//You can change 100
anchor.style.left=random(0,3000-parseInt(anchor.style.width))+"px";//If you changed 3000 from
anchor.style.top=random(0,3000-parseInt(anchor.style.height))+"px";//the top, change it here
anchor.style.backgroundColor="black";
anchor.id="Anchor"+a;
document.body.appendChild(anchor);
}
}
function getAllAnchors()
{
allAnchors=document.getElementsByTagName("a");
for(var a=0;a<allAnchors.length;a++)
{
couplesXY[a]=[];
couplesXY[a][0]=left(allAnchors[a]);
couplesXY[a][1]=top(allAnchors[a]);
}
}
function findClosestAnchor()
{
var distances=[];
for(var a=0;a<couplesXY.length;a++)distances.push(Math.pow((x-couplesXY[a][0]),2)+Math.pow((y-couplesXY[a][1]),2));//Math formula to get the distance from A to B (http://euler.ac-versailles.fr/baseeuler/lexique/notion.jsp?id=122). I removed the square root not to slow down the calculations
var smallest=distances[0];
smallestIndex=0;
for(var a=1;a<distances.length;a++)if(smallest>distances[a])
{
smallest=distances[a];
smallestIndex=a;
}
idClosest=allAnchors[smallestIndex].id;
alert(idClosest);
}
function jumpToIt()
{
window.scrollTo(couplesXY[smallestIndex][0],couplesXY[smallestIndex][1]);
allAnchors[smallestIndex].style.backgroundColor="red";//Color it to see it
}
generateRandomAnchors();
getAllAnchors();
findClosestAnchor();
jumpToIt();
Fiddle : http://jsfiddle.net/W8LBs/2
PS : If you open this fiddle on a smartphone, it doesn't work (I don't know why) but if you copy this code in a sample on a smartphone, it works (but you must specify the <html> and the <body> section).

This answer has not received enough attention.
Complete sample, fast (binary search) with caching for positions.
Fixed height and width, id of the closest anchor and scrollto
<!DOCTYPE html>
<html lang="en">
<head>
<meta>
<title>Offset 2</title>
<style>
body { font-family:helvetica,arial; font-size:12px; }
</style>
<script>
var ui = reqX = reqY = null, etop = eleft = 0, ref, cache;
function createAnchors()
{
if (!ui)
{
ui = document.getElementById('UIWebView');
reqX = document.getElementById('reqX');
reqY = document.getElementById('reqY');
var h=[], i=0;
while (i < 1000)
h.push('<a>fake anchor ... ',i,'</a> <a href=#>text for anchor <b>',(i++),'</b></a> ');
ui.innerHTML = '<div style="padding:10px;width:700px">' + h.join('') + '</div>';
cache = [];
ref = Array.prototype.slice.call(ui.getElementsByTagName('a'));
i = ref.length;
while (--i >= 0)
if (ref[i].href.length == 0)
ref.splice(i,1);
}
}
function pos(i)
{
if (!cache[i])
{
etop = eleft = 0;
var e=ref[i];
if (e.offsetParent)
{
do
{
etop += e.offsetTop;
eleft += e.offsetLeft;
} while ((e = e.offsetParent) && e != ui)
}
cache[i] = [etop, eleft];
}
else
{
etop = cache[i][0];
eleft = cache[i][1];
}
}
function find()
{
createAnchors();
if (!/^\d+$/.test(reqX.value))
{
alert ('I need a number for X');
return;
}
if (!/^\d+$/.test(reqY.value))
{
alert ('I need a number for Y');
return;
}
var
x = reqX.value,
y = reqY.value,
low = 0,
hi = ref.length + 1,
med,
limit = (ui.scrollHeight > ui.offsetHeight) ? ui.scrollHeight - ui.offsetHeight : ui.offsetHeight - ui.scrollHeight;
if (y > limit)
y = limit;
if (x > ui.scrollWidth)
x = (ui.scrollWidth > ui.offsetWidth) ? ui.scrollWidth : ui.offsetWidth;
while (low < hi)
{
med = (low + ((hi - low) >> 1));
pos(med);
if (etop == y)
{
low = med;
break;
}
if (etop < y)
low = med + 1;
else
hi = med - 1;
}
var ctop = etop;
if (eleft != x)
{
if (eleft > x)
while (low > 0)
{
pos(--low);
if (etop < ctop || eleft < x)
{
pos(++low);
break;
}
}
else
{
hi = ref.length;
while (low < hi)
{
pos(++low);
if (etop > ctop || eleft > x)
{
pos(--low);
break;
}
}
}
}
ui.scrollTop = etop - ui.offsetTop;
ui.scrollLeft = eleft - ui.offsetLeft;
ref[low].style.backgroundColor = '#ff0';
alert(
'Requested position: ' + x + ', ' + y +
'\nScrollTo position: ' + ui.scrollLeft + ', '+ ui.scrollTop +
'\nClosest anchor id: ' + low
);
}
</script>
</head>
<body>
<div id=UIWebView style="width:320px;height:480px;overflow:auto;border:solid 1px #000"></div>
<label for="req">X: <input id=reqX type=text size=5 maxlength=5 value=200></label>
<label for="req">Y: <input id=reqY type=text size=5 maxlength=5 value=300></label>
<input type=button value="Find closest anchor" onclick="find()">
</body>
</html>

Related

Javascript full screen display issues

I have been trying to put a text particle effect on my website. I have tested it on Codepen and works great but does not work on my website.
The text shows but the effect does not work as required. The text stays in a static position on the screen but the hover effect is below the word.
taking the mose through the text does nothing, if I move the mouse to the bottom of the screen the effect works on the text above.
The text stays static, however, when I move scroll down, the position of the text effect stays at the bottom of the screen until it ends up below the div and stops working all together.
I was wondering if someone could help me centre this behind the text.
Also I am keen to change the colour of the text, to a linear gradient from #125eaa to #d52027
The link to the page on my site - https://www.supplementgenie.co.uk/testpage
link to my codepen - https://codepen.io/Paulmcf87/pen/gjpgOB
However, when I run this code on JS Fiddle it gives me a 404 error?
You will see, running code below it works great as on Codepen. It doesnt seem to translate properly to a full screen
Any help would be great
The code I am using
var pixels=new Array();
var canv=$('canv');
var ctx=canv.getContext('2d');
var wordCanv=$('wordCanv');
var wordCtx=wordCanv.getContext('2d');
var mx=-1;
var my=-1;
var words="";
var txt=new Array();
var cw=0;
var ch=0;
var resolution=1;
var n=0;
var timerRunning=false;
var resHalfFloor=0;
var resHalfCeil=0;
function canv_mousemove(evt)
{
mx=evt.clientX-canv.offsetLeft;
my=evt.clientY-canv.offsetTop;
}
function Pixel(homeX,homeY)
{
this.homeX=homeX;
this.homeY=homeY;
this.x=Math.random()*cw;
this.y=Math.random()*ch;
//tmp
this.xVelocity=Math.random()*10-5;
this.yVelocity=Math.random()*10-5;
}
Pixel.prototype.move=function()
{
var homeDX=this.homeX-this.x;
var homeDY=this.homeY-this.y;
var homeDistance=Math.sqrt(Math.pow(homeDX,2) + Math.pow(homeDY,2));
var homeForce=homeDistance*0.01;
var homeAngle=Math.atan2(homeDY,homeDX);
var cursorForce=0;
var cursorAngle=0;
if(mx >= 0)
{
var cursorDX=this.x-mx;
var cursorDY=this.y-my;
var cursorDistanceSquared=Math.pow(cursorDX,2) + Math.pow(cursorDY,2);
cursorForce=Math.min(10000/cursorDistanceSquared,10000);
cursorAngle=Math.atan2(cursorDY,cursorDX);
}
else
{
cursorForce=0;
cursorAngle=0;
}
this.xVelocity+=homeForce*Math.cos(homeAngle) + cursorForce*Math.cos(cursorAngle);
this.yVelocity+=homeForce*Math.sin(homeAngle) + cursorForce*Math.sin(cursorAngle);
this.xVelocity*=0.92;
this.yVelocity*=0.92;
this.x+=this.xVelocity;
this.y+=this.yVelocity;
}
function $(id)
{
return document.getElementById(id);
}
function timer()
{
if(!timerRunning)
{
timerRunning=true;
setTimeout(timer,33);
for(var i=0;i<pixels.length;i++)
{
pixels[i].move();
}
drawPixels();
wordsTxt.focus();
n++;
if(n%10==0 && (cw!=document.body.clientWidth || ch!=document.body.clientHeight)) body_resize();
timerRunning=false;
}
else
{
setTimeout(timer,10);
}
}
function getRandomColor(min, max) {
return Math.random() * (max - min) + min;
}
function drawPixels()
{
var imageData=ctx.createImageData(cw,ch);
var actualData=imageData.data;
var index;
var goodX;
var goodY;
var realX;
var realY;
for(var i=0;i<pixels.length;i++)
{
goodX=Math.floor(pixels[i].x);
goodY=Math.floor(pixels[i].y);
for(realX=goodX-resHalfFloor; realX<=goodX+resHalfCeil && realX>=0 && realX<cw;realX++)
{
for(realY=goodY-resHalfFloor; realY<=goodY+resHalfCeil && realY>=0 && realY<ch;realY++)
{
index=(realY*imageData.width + realX)*4;
actualData[index+3]=realX;
actualData[index+2]=realX;
actualData[index+1]=realY;
}
}
}
imageData.data=actualData;
ctx.putImageData(imageData,0,0);
}
function readWords()
{
words=$('wordsTxt').value;
txt=words.split('\n');
}
function init()
{
readWords();
var fontSize=200;
var wordWidth=0;
do
{
wordWidth=0;
fontSize-=5;
wordCtx.font=fontSize+"px Avenir, sans-serif";
for(var i=0;i<txt.length;i++)
{
var w=wordCtx.measureText(txt[i]).width;
if(w>wordWidth) wordWidth=w;
}
} while(wordWidth>cw-50 || fontSize*txt.length > ch-50)
wordCtx.clearRect(0,0,cw,ch);
wordCtx.textAlign="center";
wordCtx.textBaseline="middle";
for(var i=0;i<txt.length;i++)
{
wordCtx.fillText(txt[i],cw/2,ch/2 - fontSize*(txt.length/2-(i+0.5)));
}
var index=0;
var imageData=wordCtx.getImageData(0,0,cw,ch);
for(var x=0;x<imageData.width;x+=resolution) //var i=0;i<imageData.data.length;i+=4)
{
for(var y=0;y<imageData.height;y+=resolution)
{
i=(y*imageData.width + x)*4;
if(imageData.data[i+3]>128)
{
if(index >= pixels.length)
{
pixels[index]=new Pixel(x,y);
}
else
{
pixels[index].homeX=x;
pixels[index].homeY=y;
}
index++;
}
}
}
pixels.splice(index,pixels.length-index);
}
function body_resize()
{
cw=document.body.clientWidth;
ch=document.body.clientHeight;
canv.width=cw;
canv.height=ch;
wordCanv.width=cw;
wordCanv.height=ch;
init();
}
wordsTxt.focus();
wordsTxt.value="Supplement Genie";
resolution=1;
resHalfFloor=Math.floor(resolution/2);
resHalfCeil=Math.ceil(resolution/2);
body_resize();
timer();
#wordsTxt{
display:none
}
div.pixeltext canvas{
width:98vw;
height:100vh;
}
div.pixeltext{
background-color: #d52027;
<div class="pixeltext">
<canvas id="canv" onmousemove="canv_mousemove(event);" onmouseout="mx=-1;my=-1;">
you need a canvas-enabled browser, such as Google Chrome
</canvas>
<canvas id="wordCanv" width="500px" height="500px" style="border:1px solid black;display:none;">
</canvas>
<textarea id="wordsTxt" style="position:absolute;left:-100;top:-100;" onblur="init();" onkeyup="init();" onclick="init();"></textarea>
<div>
You should define the cw,ch variables based on the canvas dimensions and not on the document.body.clientWidth etc.
Also you should avoid using canv.offsetLeft and canv.offsetTop since your element is inside other positioned elements and the offset properties return the position relative to the closest positioned ancestor.
Using canv.getBoundingClientRect which returns the width/height and top/left/right/bottom properties relative to the viewport will solve the problem.
(your codepen was also using wrong names of the methods you had created)
See https://codepen.io/gpetrioli/pen/rreagp which basically modifies the following methods
function canvMousemove(evt) {
var rect = canv.getBoundingClientRect();
mx = evt.clientX - rect.left;
my = evt.clientY - rect.top;
}
function body_resize() {
var rect = canv.getBoundingClientRect()
cw = rect.width;
ch = rect.height;
console.log(ch);
canv.width = cw;
canv.height = ch;
wordCanv.width = cw;
wordCanv.height = ch;
init();
}
In your site i noticed a timer method which should also be modified to
function timer() {
var rect;
if (!timerRunning) {
timerRunning = true;
setTimeout(timer, 33);
for (var i = 0; i < pixels.length; i++) {
pixels[i].move();
}
drawPixels();
wordsTxt.focus();
n++;
rect = canv.getBoundingClientRect();
if (n % 10 == 0 && (cw != rect.width || ch != rect.height)) body_resize();
timerRunning = false;
} else {
setTimeout(timer, 10);
}
}

Drag and Drop Javascript Puzzle

I'm trying to revive some old code I have which is a jigsaw puzzle. It loads images (puzzle pieces) from a folder, randomly places them around the page, and then you drag and drop onto the board. This used to work, but when I tried to use it today, it just throws errors (see below).
HTML:
<body onload="init();" onmousemove="initDrag();" onmouseup="mousePress=false;">
<div id="main">
<div id="inside">
<img src="holder.gif" style="position:absolute; left:500; top:500;" />
</div>
</div>
<div style="position:absolute;top:10px;left:600px;display:none;">
</div>
<p id="pText" class="congrats" style="position:absolute; top:410px; left:475px;"></p>
<p style="position:absolute; top:20px; left:750px;" class="links">hard puzzle | home</p>
</body>
Javascript:
// ARRAY FOR PLACEMENT OF IMAGES: [down, over]
var place = new Array([51,300],[51,432],[51,569],[51,707],[112,300],[112,432],[112,569],[112,707],[199,300],[199,432],[199,569],[199,707],[286,300],[286,432],[286,569],[286,707]);
var displayed = new Array();
var mousePress = false;
var pieces = place.length;
var placed = new Array();
var moveObject;
function init() {
var append = "";
for ( i=0; i<pieces; i++ )
{
append+= '<div onDrag="return false;" unselectable=on id="puzzle" name="puzzle" class="puzzleMain"><img src="img/us/img' + i + '.gif" onmousedown="mousePress=true;moveObject=' + i + ';if(document.all) {offsetX=window.event.offsetX;offsetY=window.event.offsetY;}" onmouseup="mousePress=false;doplace(' + i + ');"></div>';
displayed[i] = 0;
placed[i]=0;
}
document.getElementById("main").innerHTML += append;
document.images[i].onload = rndmImg;
}
function rndmImg() {
x=855;y=50;
do {
do {
displayNext = Math.floor( Math.random()* pieces );
} while( displayed[displayNext] );
document.getElementsByName("puzzle")[displayNext].style.top = y;
document.getElementsByName("puzzle")[displayNext].style.left = x;
document.getElementsByName("puzzle")[displayNext].style.visibility="visible";
displayed[displayNext]=1;
x += document.images[displayNext].width;
if( x >= 900 ) {
y += document.images[displayNext].height;
if ( y>=300 ) { x=0 } else { x=851 }
}
} while(!allDisplayed());
}
function allDisplayed() {
for( z=0; z<displayed.length; z++ ) if( !displayed[z] ) return false;
return true;
}
function lower() {
for( p=0;p<document.getElementsByName("puzzle").length;p++ )
document.getElementsByName("puzzle")[p].style.zIndex = 1;
document.getElementsByName("puzzle")[moveObject].style.zIndex=5;
}
function initDrag(e) {
if(!mousePress)return;
if( document.getElementById("inside").innerHTML != "" ) document.getElementById("inside").innerHTML = "";
lower();
if(document.all) {
mouseX = window.event.clientX - (offsetX);
mouseY = window.event.clientY - (offsetY);
} else {
mouseX = e.clientX - 50;
mouseY = e.clientY - 50;
}
document.getElementsByName("puzzle")[moveObject].style.top=mouseY;
document.getElementsByName("puzzle")[moveObject].style.left=mouseX;
return false;
}
function doplace(index) {
w = document.images[index].width;
h = document.images[index].height;
t = parseInt(document.getElementsByName("puzzle")[index].style.top);
l = parseInt(document.getElementsByName("puzzle")[index].style.left);
if ( ( l >= place[index][1]-(w/2) && l <= place[index][1]+(w/2) ) && ( t >= place[index][0]-(h/2) && t <= place[index][0] + (h/2) ) )
{
document.getElementsByName("puzzle")[index].style.top = place[index][0];
document.getElementsByName("puzzle")[index].style.left = place[index][1];
placed[index] = 1;
if(isComplete())
pText.innerHTML = "Puzzle is complete!";
}
}
function generateArray()
{
append="var place = new Array(";
for( i=0; i<document.getElementsByName("puzzle").length; i++ )
{
t = document.getElementsByName("puzzle")[i].style.pixelTop;
l = document.getElementsByName("puzzle")[i].style.pixelLeft;
append+="[" + t + "," + l + "],";
}
document.forms[0].mArray.value = append;
}
function isComplete()
{
for( q=0;q<placed.length;q++ ) if( !placed[q] )return false;
return true;
}
The error I mostly get is: Uncaught TypeError: Cannot read property 'clientX' of undefined
at initDrag (easy.html:70)
at HTMLBodyElement.onmousemove (easy.html:116)
I have a JSFiddle here. Can anyone shed some light on what the issue might be?
In your code you have onmousemove="initDrag();" so if document.all is falsy then mouseX = e.clientX - 50 would throw a Cannot read property 'clientX' of undefined because you call initDrag() without any argument on mouse move.
Now adays you neither should use document.all nor window.event, both are relicts.

How to display only one image in ezpublish JS slider

I'm a beginner php developer, and have a shockingly poor fluency in Javascript. An ezpublish website I'm working on has this slider in as a default piece of code, but it displays three items. How can I edit it to show only 1 item? The code is:
(function() {
YUI( YUI3_config ).use( 'node', 'event', 'io-ez', function(Y, result) {
Y.on('domready', function(e) {
var offset = 0;
var limit = 1;
var total = {$block.valid_nodes|count()};
var handleRequest = function(e) {
var className = e.target.get('className');
if ( className == 'carousel-next-button' ) {
offset += 1;
if ( offset > total )
offset = 0;
}
if ( className == 'carousel-prev-button' ) {
var diff = total - offset;
if( offset == 0 )
offset = 0;
else
offset -= 1;
}
var colContent = Y.Node.all('#block-3 .col-content');
colContent.each(function(n, e) {
n.addClass('loading');
var height = n.get('region').bottom - n.get('region').top;
n.setStyle('height', height + 'px');
n.set('innerHTML', '');
});
var data = 'http_accept=json&offset=' + offset;
data += '&limit=' + limit;
data += '&block_id={$block.id}';
Y.io.ez( 'ezflow::getvaliditems', { on: { success: _callBack
}, method: 'POST', data: data } );
};
var _callBack = function(id, o) {
if ( o.responseJSON !== undefined ) {
var response = o.responseJSON;
var colContent = Y.Node.all('#block-{$block.id} .col-content');
for(var i = 0; i < colContent.size(); i++) {
var colNode = colContent.item(i);
if ( response.content[i] !== undefined )
colNode.set('innerHTML', response.content[i] );
}
}
};
var prevButton = Y.one('#block-{$block.id} input.carousel-prev-button');
prevButton.on('click', handleRequest);
var nextButton = Y.one('#block-{$block.id} input.carousel-next-button');
nextButton.on('click', handleRequest);
});
});
})();
</script>
A hand with this would be great x
Looks to me like this code loads each item after the user clicks prevButton or nextButton. So the simplest way to force only a single item to display is probably to hide those buttons.
Without the markup it's hard to say what the optimal solution is, but I would try to find out what makes the particular markup you're working with into a carousel (I'd guess a class containing "carousel") and remove that so that it's just a single item without the carousel functionality.
For what it's worth, this question is not specific to eZ Publish or PHP so I'd consider removing those tags.

PaperJS - How do I connect all items that have a distance of X from any given item? (Item interactivity)

I have a project I am trying to get an animated <canvas> working with Paper JS. What I am curious about is if there is anything built into PaperJS that allows the ability to detect interactivity between items (i.e. if a item is X distance from any other item on the layer). Here is what I have so far:
HTML
<canvas id="myCanvas" resize></canvas>
CSS
html, body{margin:0; padding: 0;}
#myCanvas{width: 100%; height: 100%;}
JS
$(function(){
var canvas = $('#myCanvas')[0];
paper.setup(canvas);
var viewSize = paper.view.size;
var itemCount = 20;
var theBall = new paper.Path.Rectangle({
point : [0,0],
size : 10,
fillColor : '#00a950',
});
var theBallSymbol = new paper.Symbol(theBall);
// Create and place symbol on view
for (var i = 1; i <= itemCount; i++) {
var center = paper.Point.random().multiply(viewSize);
var placedSymbol = theBallSymbol.place(center);
placedSymbol.scale(i / itemCount);
placedSymbol.data = {
origin : center,
direction : (Math.round(Math.random())) ? 'right' : 'left',
}
placedSymbol.onFrame = function(e){
var pathWidth = this.bounds.width * 20;
var center = this.data.origin;
var moveValue = this.bounds.width / 20;
if(this.data.direction == 'right'){
if(this.position.x < center.x + pathWidth){
this.position.x += moveValue;
} else{
this.position.x -= moveValue;
this.data.direction = 'left';
}
} else {
if(this.position.x > center.x - pathWidth){
this.position.x -= moveValue;
} else {
this.position.x += moveValue;
this.data.direction = 'right';
}
}
}
}
paper.view.onFrame = function (e){
// For entire view
for (var i = 0; i < itemCount; i++) {
var item = paper.project.activeLayer.children[i];
// I imagine I would need to do something here
// I tried a hitTest already, but I'm not sure
// that will give me the information I would need
}
}
});
JSFiddle
That part so far is working well. What I am curious about how I can do the following:
Whenever any given item (the squares) come within a distance of X between each other, create a line (path) between them
The idea is very similar to this page: http://panasonic.jp/shaver/lamdash/dna/
Any ideas would be greatly appreciated. Thanks!
Paper.js does not keep track of the inter-point distance between an item's center and all other items. The only way to gather that information is to manually loop through them.
In your case, I think it would be easiest to:
Create an array of lines
Only keep lines that might become shorter than the threshold value
Loop through the lines array on each onFrame() and adjust the opacity.
By only choosing lines that will come within a threshold value, you can avoid creating unnecessary paths that would slow the framerate. Without this, you'd be checking ~5 times as many items.
Here's a quick example:
$(function(){
var canvas = $('#myCanvas')[0];
paper.setup(canvas);
var viewSize = paper.view.size;
var itemCount = 60;
//setup arrays to change line segments
var ballArray = [];
var lineArray = [];
//threshold distance for lines
var threshold = Math.sqrt(paper.view.size.width*paper.view.size.height)/5;
var theBall = new paper.Path.Rectangle({
point : [0,0],
size : 10,
fillColor : '#00a950',
});
var theBallSymbol = new paper.Symbol(theBall);
// Create and place symbol on view
for (var i = 1; i <= itemCount; i++) {
var center = paper.Point.random().multiply(viewSize);
var placedSymbol = theBallSymbol.place(center);
placedSymbol.scale(i / itemCount);
placedSymbol.data = {
origin : center,
direction : (Math.round(Math.random())) ? 'right' : 'left',
}
// Keep each placedSymbol in an array
ballArray.push( placedSymbol );
placedSymbol.onFrame = function(e){
var pathWidth = this.bounds.width * 20;
var center = this.data.origin;
var moveValue = this.bounds.width / 20;
if(this.data.direction == 'right'){
if(this.position.x < center.x + pathWidth){
this.position.x += moveValue;
} else{
this.position.x -= moveValue;
this.data.direction = 'left';
}
} else {
if(this.position.x > center.x - pathWidth){
this.position.x -= moveValue;
} else {
this.position.x += moveValue;
this.data.direction = 'right';
}
}
}
}
// Run through every possible line
// Only keep lines whose length might become less than threshold
for (var i = 0; i < itemCount; i++) {
for (j = i + 1, point1 = ballArray[i].data.origin; j < itemCount; j++) {
if ( Math.abs(point1.y - ballArray[j].bounds.center.y) < threshold && Math.abs(point1.x - ballArray[j].data.origin.x) < 4 * threshold) {
var line = new paper.Path.Line( point1, ballArray[j].bounds.center ) ;
line.strokeColor = 'black';
line.strokeWidth = .5;
//note the index of the line's segments
line.point1 = i;
line.point2 = j;
if (line.length > 1.4 * threshold && ballArray[j].data.direction == ballArray[i].data.direction) {
line.remove();
}
else {
lineArray.push(line);
}
}
}
}
paper.view.onFrame = function (e){
// Update the segments of each line
// Change each line's opacity with respect to distance
for (var i = 0, l = lineArray.length; i < l; i++) {
var line = lineArray[i];
line.segments[0].point = ballArray[line.point1].bounds.center;
line.segments[1].point = ballArray[line.point2].bounds.center;
if(line.length < threshold) {
line.opacity = (threshold - line.length) / threshold;
}
else line.opacity = 0;
}
}
});

Apply drag and drop/attach feature to JSTreegraph using Jquery draggable

I am using JSTreegraph plugin to draw a tree structure.
But now I need a drag, drop and attach feature wherein I can drag any node of the tree and attach to any other node and subsequently all the children of the first node will be now the grand-children of the new node (to which it is attached).
As far as I know this plugin doesnt seem to have this feature. It simply draws the structure based on the data object passed to it.
The plugin basically assigns a class Node to all the nodes(divs) of the tree and another class NodeHover to a node on hover. No id is assigned to these divs.
So I tried using JQuery Draggable just to see if any of the node can be moved by doing this
$('.Node').draggable();
$('.NodeHover').draggable();
But it doesnt seem to work. So can anyone help me with this.
How can I get drag and attach functionality?
*EDIT:: Pardon me am not so great with using Fiddle, so am sharing a sample code here for your use:*
HTML file: which will draw the sample tree
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="css/JSTreeGraph.css" rel="stylesheet" type="text/css" />
<script src="js/JSTreeGraph.js" type="text/javascript"></script>
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery.ui.position.js" type="text/javascript"></script>
<style type="text/css">
.Container {
position: absolute;
top: 100px;
left: 50px;
id: Container;
}
</style>
</head>
<body>
<div id="tree">
Ctrl+Click to Add Node
<br />
Double Click to Expand or Collapse
<br />
Shift+Click to Delete Node
<br />
<select id="dlLayout" onchange="ChangeLayout()">
<option value="Horizontal">
Horizontal
</option>
<option value="Vertical" selected>
Vertical
</option>
</select>
<div class="Container" id="dvTreeContainer"></div>
<script type="text/javascript">
var selectedNode;
// Root node
var rootNode = { Content: "Onida", Nodes:[] };
// First Level
rootNode.Nodes[0] = { Content: "Employee Code", navigationType: "0"};
rootNode.Nodes[1] = { Content: "Problem Area", navigationType: "1" };
// Second Level
rootNode.Nodes[1].Nodes = [{ Content : "ACC-HO", Collapsed: true /* This node renders collapsed */ },
{ Content : "ACC-SALES" },
{ Content : "BUSI. HEAD", /*This node looks different*/ ToolTip: "Click ME!" },
{ Content : "CEO"},
{ Content : "HO-ADMIN"},
{ Content : "HO-FACTORY"},
{ Content : "SALES"}];
// Third Level
rootNode.Nodes[1].Nodes[0].Nodes = [{ Content: "Billing" },
{ Content: "Credit Limit" },
{ Content: "Reconciliation" }];
rootNode.Nodes[1].Nodes[1].Nodes = [{ Content: "Billing" },
{ Content: "Others" }];
rootNode.Nodes[1].Nodes[2].Nodes = [{ Content: "AC" },
{ Content: "CTV" },
{ Content: "DVD" },
{ Content: "Washing Machine" }];
rootNode.Nodes[1].Nodes[6].Nodes = [{ Content: "Appointments" },
{ Content: "Resignations" },
{ Content: "Others" }];
// Draw the tree for the first time
RefreshTree();
function RefreshTree() {
DrawTree({ Container: document.getElementById("dvTreeContainer"),
RootNode: rootNode,
Layout: document.getElementById("dlLayout").value,
OnNodeClickFirefox: NodeClickFF,
OnNodeClickIE: NodeClickIE,
OnNodeDoubleClick: NodeDoubleClick
});
}
//function
function NodeClickFF(e) {
if (e.shiftKey){
// Delete Node
if (!this.Node.Collapsed) {
for(var index=0; index<this.Node.ParentNode.Nodes.length; index++) {
if(this.Node.ParentNode.Nodes[index].Content == this.Node.Content) {
this.Node.ParentNode.Nodes.splice(index, 1);
break;
}
}
RefreshTree();
}
// return false;
}
else if (e.ctrlKey) {
// Add new Child if Expanded
if (!this.Node.Collapsed) {
if (!this.Node.Nodes) this.Node.Nodes = new Array();
var newNodeIndex = this.Node.Nodes.length;
this.Node.Nodes[newNodeIndex] = new Object();
this.Node.Nodes[newNodeIndex].Content = this.Node.Content + "." + (newNodeIndex + 1);
RefreshTree();
}
// return false;
}
else{
fnNodeProperties(this.Node);
}
}
function NodeClickIE() {
if (typeof(event) == "undefined" && event.ctrlKey) {
// Add new Child if Expanded
if (!this.Node.Collapsed) {
if (!this.Node.Nodes) this.Node.Nodes = new Array();
var newNodeIndex = this.Node.Nodes.length;
this.Node.Nodes[newNodeIndex] = new Object();
this.Node.Nodes[newNodeIndex].Content = this.Node.Content + "." + (newNodeIndex + 1);
RefreshTree();
}
}
else if (typeof(event) == "undefined" && event.shiftKey) {
// Delete Node
if (!this.Node.Collapsed) {
for(var index=0; index<this.Node.ParentNode.Nodes.length; index++) {
if(this.Node.ParentNode.Nodes[index].Content == this.Node.Content) {
this.Node.ParentNode.Nodes.splice(index, 1);
break;
}
}
RefreshTree();
}
}
else{
fnNodeProperties(this.Node);
}
}
function NodeDoubleClick() {
if (this.Node.Nodes && this.Node.Nodes.length > 0) { // If has children
this.Node.Collapsed = !this.Node.Collapsed;
RefreshTree();
}
}
function ChangeLayout() {
RefreshTree();
}
</script>
</div>
</body>
</html>
JSTreeGraph JS file: plugin js file
function DrawTree(options) {
// Prepare Nodes
PrepareNode(options.RootNode);
// Calculate Boxes Positions
if (options.Layout == "Vertical") {
PerformLayoutV(options.RootNode);
} else {
PerformLayoutH(options.RootNode);
}
// Draw Boxes
options.Container.innerHTML = "";
DrawNode(options.RootNode, options.Container, options);
// Draw Lines
DrawLines(options.RootNode, options.Container);
}
function DrawLines(node, container) {
if ((!node.Collapsed) && node.Nodes && node.Nodes.length > 0) { // Has children and Is Expanded
for (var j = 0; j < node.Nodes.length; j++) {
if(node.ChildrenConnectorPoint.Layout=="Vertical")
DrawLineV(container, node.ChildrenConnectorPoint, node.Nodes[j].ParentConnectorPoint);
else
DrawLineH(container, node.ChildrenConnectorPoint, node.Nodes[j].ParentConnectorPoint);
// Children
DrawLines(node.Nodes[j], container);
}
}
}
function DrawLineH(container, startPoint, endPoint) {
var midY = (startPoint.Y + ((endPoint.Y - startPoint.Y) / 2)); // Half path between start en end Y point
// Start segment
DrawLineSegment(container, startPoint.X, startPoint.Y, startPoint.X, midY, 1);
// Intermidiate segment
var imsStartX = startPoint.X < endPoint.X ? startPoint.X : endPoint.X; // The lower value will be the starting point
var imsEndX = startPoint.X > endPoint.X ? startPoint.X : endPoint.X; // The higher value will be the ending point
DrawLineSegment(container, imsStartX, midY, imsEndX, midY, 1);
// End segment
DrawLineSegment(container, endPoint.X, midY, endPoint.X, endPoint.Y, 1);
}
function DrawLineV(container, startPoint, endPoint) {
var midX = (startPoint.X + ((endPoint.X - startPoint.X) / 2)); // Half path between start en end X point
// Start segment
DrawLineSegment(container, startPoint.X, startPoint.Y, midX, startPoint.Y, 1);
// Intermidiate segment
var imsStartY = startPoint.Y < endPoint.Y ? startPoint.Y : endPoint.Y; // The lower value will be the starting point
var imsEndY = startPoint.Y > endPoint.Y ? startPoint.Y : endPoint.Y; // The higher value will be the ending point
DrawLineSegment(container, midX, imsStartY, midX, imsEndY, 1);
// End segment
DrawLineSegment(container, midX, endPoint.Y, endPoint.X, endPoint.Y, 1);
}
function DrawLineSegment(container, startX, startY, endX, endY, lineWidth) {
var lineDiv = document.createElement("div");
lineDiv.style.top = startY + "px";
lineDiv.style.left = startX + "px";
if (startX == endX) { // Vertical Line
lineDiv.style.width = lineWidth + "px";
lineDiv.style.height = (endY - startY) + "px";
}
else{ // Horizontal Line
lineDiv.style.width = (endX - startX) + "px";
lineDiv.style.height = lineWidth + "px";
}
lineDiv.className = "NodeLine";
container.appendChild(lineDiv);
}
function DrawNode(node, container, options) {
var nodeDiv = document.createElement("div");
nodeDiv.style.top = node.Top + "px";
nodeDiv.style.left = node.Left + "px";
nodeDiv.style.width = node.Width + "px";
nodeDiv.style.height = node.Height + "px";
if (node.Collapsed) {
nodeDiv.className = "NodeCollapsed";
} else {
nodeDiv.className = "Node";
}
if (node.Class)
nodeDiv.className = node.Class;
if (node.Content)
nodeDiv.innerHTML = "<div class='NodeContent'>" + node.Content + "</div>";
if (node.ToolTip)
nodeDiv.setAttribute("title", node.ToolTip);
nodeDiv.Node = node;
// Events
if (options.OnNodeClickIE){
//alert('OnNodeClick');
nodeDiv.onclick = options.OnNodeClickIE;
}
// Events
if (options.OnNodeClickFirefox){
//alert('OnNodeClick');
nodeDiv.onmousedown = options.OnNodeClickFirefox;
}
//on right click
if (options.OnContextMenu){
//alert('OnContextMenu');
nodeDiv.oncontextmenu = options.OnContextMenu;
}
if (options.OnNodeDoubleClick)
nodeDiv.ondblclick = options.OnNodeDoubleClick;
nodeDiv.onmouseover = function () { // In
this.PrevClassName = this.className;
this.className = "NodeHover";
};
nodeDiv.onmouseout = function () { // Out
if (this.PrevClassName) {
this.className = this.PrevClassName;
this.PrevClassName = null;
}
};
container.appendChild(nodeDiv);
// Draw children
if ((!node.Collapsed) && node.Nodes && node.Nodes.length > 0) { // Has Children and is Expanded
for (var i = 0; i < node.Nodes.length; i++) {
DrawNode(node.Nodes[i], container, options);
}
}
}
function PerformLayoutV(node) {
var nodeHeight = 30;
var nodeWidth = 100;
var nodeMarginLeft = 40;
var nodeMarginTop = 20;
var nodeTop = 0; // defaultValue
// Before Layout this Node, Layout its children
if ((!node.Collapsed) && node.Nodes && node.Nodes.length > 0) {
for (var i = 0; i < node.Nodes.length; i++) {
PerformLayoutV(node.Nodes[i]);
}
}
if ((!node.Collapsed) && node.Nodes && node.Nodes.length > 0) { // If Has Children and Is Expanded
// My Top is in the center of my children
var childrenHeight = (node.Nodes[node.Nodes.length - 1].Top + node.Nodes[node.Nodes.length - 1].Height) - node.Nodes[0].Top;
nodeTop = (node.Nodes[0].Top + (childrenHeight / 2)) - (nodeHeight / 2);
// Is my top over my previous sibling?
// Move it to the bottom
if (node.LeftNode && ((node.LeftNode.Top + node.LeftNode.Height + nodeMarginTop) > nodeTop)) {
var newTop = node.LeftNode.Top + node.LeftNode.Height + nodeMarginTop;
var diff = newTop - nodeTop;
/// Move also my children
MoveBottom(node.Nodes, diff);
nodeTop = newTop;
}
} else {
// My top is next to my top sibling
if (node.LeftNode)
nodeTop = node.LeftNode.Top + node.LeftNode.Height + nodeMarginTop;
}
node.Top = nodeTop;
// The Left depends only on the level
node.Left = (nodeMarginLeft * (node.Level + 1)) + (nodeWidth * (node.Level + 1));
// Size is constant
node.Height = nodeHeight;
node.Width = nodeWidth;
// Calculate Connector Points
// Child: Where the lines get out from to connect this node with its children
var pointX = node.Left + nodeWidth;
var pointY = nodeTop + (nodeHeight/2);
node.ChildrenConnectorPoint = { X: pointX, Y: pointY, Layout: "Vertical" };
// Parent: Where the line that connect this node with its parent end
pointX = node.Left;
pointY = nodeTop + (nodeHeight/2);
node.ParentConnectorPoint = { X: pointX, Y: pointY, Layout: "Vertical" };
}
function PerformLayoutH(node) {
var nodeHeight = 30;
var nodeWidth = 100;
var nodeMarginLeft = 20;
var nodeMarginTop = 50;
var nodeLeft = 0; // defaultValue
// Before Layout this Node, Layout its children
if ((!node.Collapsed) && node.Nodes && node.Nodes.length>0) {
for (var i = 0; i < node.Nodes.length; i++) {
PerformLayoutH(node.Nodes[i]);
}
}
if ((!node.Collapsed) && node.Nodes && node.Nodes.length > 0) { // If Has Children and Is Expanded
// My left is in the center of my children
var childrenWidth = (node.Nodes[node.Nodes.length-1].Left + node.Nodes[node.Nodes.length-1].Width) - node.Nodes[0].Left;
nodeLeft = (node.Nodes[0].Left + (childrenWidth / 2)) - (nodeWidth / 2);
// Is my left over my left node?
// Move it to the right
if(node.LeftNode&&((node.LeftNode.Left+node.LeftNode.Width+nodeMarginLeft)>nodeLeft)) {
var newLeft = node.LeftNode.Left + node.LeftNode.Width + nodeMarginLeft;
var diff = newLeft - nodeLeft;
/// Move also my children
MoveRigth(node.Nodes, diff);
nodeLeft = newLeft;
}
} else {
// My left is next to my left sibling
if (node.LeftNode)
nodeLeft = node.LeftNode.Left + node.LeftNode.Width + nodeMarginLeft;
}
node.Left = nodeLeft;
// The top depends only on the level
node.Top = (nodeMarginTop * (node.Level + 1)) + (nodeHeight * (node.Level + 1));
// Size is constant
node.Height = nodeHeight;
node.Width = nodeWidth;
// Calculate Connector Points
// Child: Where the lines get out from to connect this node with its children
var pointX = nodeLeft + (nodeWidth / 2);
var pointY = node.Top + nodeHeight;
node.ChildrenConnectorPoint = { X: pointX, Y: pointY, Layout:"Horizontal" };
// Parent: Where the line that connect this node with its parent end
pointX = nodeLeft + (nodeWidth / 2);
pointY = node.Top;
node.ParentConnectorPoint = { X: pointX, Y: pointY, Layout: "Horizontal" };
}
function MoveRigth(nodes, distance) {
for (var i = 0; i < nodes.length; i++) {
nodes[i].Left += distance;
if (nodes[i].ParentConnectorPoint) nodes[i].ParentConnectorPoint.X += distance;
if (nodes[i].ChildrenConnectorPoint) nodes[i].ChildrenConnectorPoint.X += distance;
if (nodes[i].Nodes) {
MoveRigth(nodes[i].Nodes, distance);
}
}
}
function MoveBottom(nodes, distance) {
for (var i = 0; i < nodes.length; i++) {
nodes[i].Top += distance;
if (nodes[i].ParentConnectorPoint) nodes[i].ParentConnectorPoint.Y += distance;
if (nodes[i].ChildrenConnectorPoint) nodes[i].ChildrenConnectorPoint.Y += distance;
if (nodes[i].Nodes) {
MoveBottom(nodes[i].Nodes, distance);
}
}
}
function PrepareNode(node, level, parentNode, leftNode, rightLimits) {
if (level == undefined) level = 0;
if (parentNode == undefined) parentNode = null;
if (leftNode == undefined) leftNode = null;
if (rightLimits == undefined) rightLimits = new Array();
node.Level = level;
node.ParentNode = parentNode;
node.LeftNode = leftNode;
if ((!node.Collapsed) && node.Nodes && node.Nodes.length > 0) { // Has children and is expanded
for (var i = 0; i < node.Nodes.length; i++) {
var left = null;
if (i == 0 && rightLimits[level]!=undefined) left = rightLimits[level];
if (i > 0) left = node.Nodes[i - 1];
if (i == (node.Nodes.length-1)) rightLimits[level] = node.Nodes[i];
PrepareNode(node.Nodes[i], level + 1, node, left, rightLimits);
}
}
}
JSTreeGraph CSS file:
.NodeContent
{
font-family:Verdana;
font-size:small;
}
.Node
{
position:absolute;
background-color: #CCDAFF;
border: 1px solid #5280FF;
text-align:center;
vertical-align:middle;
cursor:pointer;
overflow:hidden;
}
.NodeHover
{
position:absolute;
background-color: #8FADFF;
border: 1px solid #5280FF;
text-align:center;
vertical-align:middle;
cursor:pointer;
overflow:hidden;
}
.NodeCollapsed
{
position:absolute;
background-color: #8FADFF;
border: 2px solid black;
text-align:center;
vertical-align:middle;
cursor:pointer;
overflow:hidden;
}
.NodeLine
{
background-color: #000066;
position:absolute;
overflow:hidden;
}
I supose that what you need is to stablish a mechanism to modify your tree logic structure on dragging and then reload the whole tree element. This way the plugin will render your new modified structure.
This is not an easy problem and you have not outlined the exact specifications.
When you move a node, should all child nodes move with it?
What happens to a node and its child elements when a node is dropped/attached?
The plugin that you are using works well for drawing static trees, but it is not written in such a way to allow for dynamically editing the tree.
I have to agree with #Bardo in that the easiest way to make this work for your needs is to understand how the tree has been manipulated. (Thankfully the plugin seems to provide an onNodeClick option which will allow you to understand which node you are intending to manipulate). Once the tree has been manipulated then it must be completely redrawn. (There doesn't appear to be a good way to partially draw a tree).

Categories

Resources