Forum Moderators: open
I'm calling my javascript like this:
<a id="changeCityLink" href="#" onClick="showAreaSelector('changeCityLink','citySelector');return false">change location</a>
and my actual javascript is:
function showAreaSelector(link_id, div_id){//getting the link
var link = $(link_id);
//getting the div
var div = $(div_id);
//determining it's location
var link_x = getX(link);
var link_y = getY(link);
//moving the div to the location of the link, slightly under and to the right
var div_x = link_x + link.width;
var div_y = link_y + link.height;
//setting the div's visibility and position
div.setAttribute("style","left:" + div_x + "px; top:" + div_y + "px; display:block;");
}
But nothing happens when I click the link. I'm perplexed. For what it's worth, the div I'm trying to show/hide is on the same page as my link:
<div id="citySelector" style="display:none;">
<span class="close"><a href="#" onClick="hideAreaSelector('citySelector');">close [x]</a></span>
Click on a city:<br/>
Can somebody help me? I'm stumped!
read this page
[howtocreate.co.uk...]
To find the position of the link you need to use offsetLeft and offsetTop which work in both IE and FF. But this will only give you position from the container, not from actual 0,0, so you will have to cycle up the DOM until you get to the top.
Next, offsetHeight and offsetWidth will give you the size of the link, no tricks here!
Also, when you set the style, you can manipulate the CSS directly, without having to set the style attibute.
Try this code......
function findPosX( obj) {
var curleft = 0;if (obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft;
obj = obj.offsetParent;
}
} else if (obj.x)
curleft += obj.x;return curleft;
}function findPosY( obj) {
var curtop = 0;if (obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
} else if (obj.y)
curtop += obj.y;return curtop;
}function showAreaSelector(link_id, div_id){
//getting the link
var link = $(link_id);
//getting the div
var div = $(div_id);
//determining it's location
var link_x = getPosX( link);
var link_y = getPosY( link);//moving the div to the location of the link, slightly under and to the right
var div_x = link_x + link.offsetWidth;
var div_y = link_y + link.offsetHeight;//setting the div's visibility and position
div.style.left = div_x;
div.style.top = div_y;
div.style.display = "block";
}
Let us know how you get on.
function findPosX( obj) {
var curleft = 0;if (obj.offsetParent) {
curleft = obj.offsetLeft;
curleft += findPosX( obj.offsetParent);} else if( obj.x)
curleft = obj.x;return curleft;
}function findPosY( obj) {
var curtop = 0;if (obj.offsetParent) {
curtop = obj.offsetTop;
curtop += findPosY( obj.offsestParent);} else if (obj.y)
curtop += obj.y;return curtop;
}
That's a bit tidier, haven't tested it but should work. Bit of a strain on the stack but in this context shouldn't be too many iterations.