Javascript style using getBoundingClientRect not working - javascript

Hi I am trying to use getBoundingClientRect javascript function but the problem is this only seems to work for 1 of my elements. Here is the code.
function getDataXML(getID, cellId) {
var divMain = document.getElementById('Main');
var divCell = document.getElementById(cellId);
var divHoverControl = document.getElementById(getID);
var rectMain = divHoverControl.getBoundingClientRect();
var rectCell = divCell.getBoundingClientRect();
var divWidth = divHoverControl.offsetWidth;
var cellWidth = divCell.offsetWidth;
alert(rectMain.left + " " + rectMain.right + " " + divWidth + " " + cellWidth);
}
Its seems as though the page gets the elements using there ID correctly as I get no error and setting some style attributes works for each element but I only seem to get a result for my rectCell and cellWidth variables but the exact same code for rectMain and DivWidth dont seem to work. Any help would be greatly appreciated.

Related

Trouble getting div elements positioned at random X/Y

// T duplicates the selected element(s).
case 116:
elementSel = document.querySelectorAll("div.selected");
var elementClone,
tmp = getBrowserWidth(),
bww = tmp[0],
bwh = tmp[1];
for (i = 0; i < elementSel.length; i++) {
elementClone = elementSel[i].cloneNode(true);
elementClone.id = "boxID" + Math.floor((1 + Math.random()) * 0x10000);
elementClone.zIndex = "+1";
var posx = getRandomInt(1, bww) - elementSel[i].offsetWidth;
var posy = getRandomInt(1, bwh) - elementSel[i].offsetHeight;
elementClone.style.left = posx + " px";
elementClone.style.top = posy + " px";
elementSel[i].appendChild(elementClone);
elementSel[i].classList.toggle("selected");
console.log("Created " + elementSel.length + " elements.");
}
I am stuck doing a school assignment. I have tried to read similar questions but I do not get any further. The problem is elementClone.style.left/.top not getting assigned new values. Why?
Related answer:
It is working for me, may be the reason is you need to change the position and float attributes.
Ok, I solved it. The problem was " px". Crappé!

Responsive Smooth Scroll CSS3 Animation?

I've been trying to get a smooth scroll animation for a while now, but mainly in JS..
This hasn't been working out that well so I decided to try in CSS3.
Now I want to make this animation responsive by calling a JS function which adds the CSS rules for the animation responsive to the object the animation is for. Here is the JS code I've got so far. I'll also leave a Fiddle, but I'm new to that so things might not work right away.
function getTexts() {
var element = document.getElementsByClassName('toplink');
for (x = 0, len = element.length; x < len; x++){
var ID = element[x].textContent.toLowerCase();
var object = document.getElementById(ID);
console.log(object);
addCSSAnimator(ID);
}
}
function addCSSAnimator(el) {
var sheet = document.styleSheets[0];
var DOM = document.getElementById(el);
var Class = DOM.getAttribute("class");
var Parent = DOM.parentElement.getAttribute("id");
var rect = DOM.getBoundingClientRect();
var rule = ".toplink[ id= '"+el+"' ]:target - #"+Parent+" div."+Class+" {\n" +
"-webkit-transform: translateY( +"+rect.y.toPrecision(4)+'px'+" );\n" +
"transform: translateY( +"+rect.y.toPrecision(4)+'px'+" );\n" +
"}";
console.log("Stylesheet: ",sheet," object: ",DOM," Class: ",Class," offset X&Y:",rect.x," ",rect.y);
console.log(rule);
sheet.insertRule("body { background-color: 0; }", 1);
}
https://jsfiddle.net/dtj46c64/
You may try moving to jquery for this solution. Use document.ready and window.resize functions to handle the animation and also instead of for loop. use the jquery .each() function to get the elements. Try working around the following code i changed for you to go along with. Hope this puts you in the right direction to achieve your goal:
<script>
function getTexts() {
$(".toplink").each(function () {
let ID = $(this)
console.log(ID);
addCSSAnimator(ID);
});
}
function addCSSAnimator(el) {
var sheet = document.styleSheets[0];
var DOM = el;
var Class = DOM.attr("class");
var Parent = DOM.parent().attr("id");
var rect = DOM[0].getBoundingClientRect();
var rule = ".toplink[ id= '" + el + "' ]:target - #" + Parent + " div." + Class + " {\n" +
"-webkit-transform: translateY( +" + rect.top.toPrecision(4) + 'px' + " );\n" +
"transform: translateY( +" + rect.top.toPrecision(4) + 'px' + " );\n" +
"}";
console.log("Stylesheet: ", sheet, " object: ", DOM, " Class: ", Class, " offset X&Y:", rect.left, " ", rect.top);
console.log(rule);
sheet.insertRule("body { background-color: 0; }", 1);
}
$(window).on('resize', function () {
getTexts();
});
$(document).ready(function () {
getTexts();
});
</script>
Notice i changed the rect.y to rect.top as on some browsers the getBoundingClientRect fucntion does not return x and y values but left and top are always filled.
Also dont know why you are getting id of the parent of the object as there is no id set to the parent of the anchor class="toplink" so it will always return as null or empty.
Sorry for not a 100% answer as got busy but i hope the solution so far i suggested will help you tweak and find what your looking for.

window.opener.document access denied?

So, I was hoping you guys could find the logic here?
So after a bit of looking all I've found was access denied errors for the window.opener thing, but it seems to be something else for me. Because I can access that and some of its properties like 'closed'.
I must be doing something wrong here...
My code:
The function that opens it (in a script tag on the parent page)
function openPopup(objectID) {
var webpagina = "Fotos.aspx";
var param = "objectid=" + objectID + "&edit=true";
var naam = "Fotos";
var height = 500;
var width = 300;
var top = 250;
var left = 400;
var scroll = "Yes";
var resize = "Yes";
var newhref = webpagina + "?" + param;
var popupwindow = window.open(newhref, naam, "toolbar=yes,titlebar=no,location=no,directories=no,status=no,menubar=no,scrollbars=" + scroll + ",resizable=" + resize + ",width=" + width + ",height=" + height + ",top=" + top + ",left=" + left);
popupwindow.opener = window;
popupwindow.focus();
}
The onload function in the opened page:
window.onload = function () {
var isclosed = window.opener.closed; //false
var secretfield = window.opener.document.getElementById('scrtFoto');
};
The access denied happens on the document, but not the closed, which is false. It's so weird, any help appreciated!
Thanks in advance!
You don't need to set the window.opener property, it's automatically set when you open your popup. Being able to set it manually would be a security risk.
What you need is contentWindow.
window.opener.contentWindow. document.getElementById('scrtFoto');

JS Fine in FF, bugged in Chrome

I built a page that uses a simple JSon table and JS/JQ to present that data. Hosted together on one sheet it works fine in both Chrome and FF. Split into seperate HTML, CSS, JS and JSON files, however, there is a slightly variable bug in Chrome.
Page: http://www.lafairclough.co.uk/JTest/index.html
Select two options from the drop down and the charts on the right should show the relative performance data from two cars (top to bottom: 0-60, 0-100, Standing Qtr and Top Speed). These are colour coded with green being the faster result and orange denoting a draw for a given variable.
The charts are made using Java to calculate and set a CSS div width. In Chrome, however, this div width is (sometimes, but often) getting calculated as a much higher figured than expected. As flows:
// Perf. BAR CHART SIZE CSS CAR A
$.getJSON("cars.json", function (data) {
$(document).ready(function () {
$('#dropdown1').change(function () {
var index = parseInt($(this).val()),
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carA060").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].zero60 * 10;
$(".carA060").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carA0100").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].zero100 * 5;
$(".carA0100").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carAsQTR").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].sQTR * 5;
$(".carAsQTR").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carAvMAX").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].vMAX * 0.5;
$(".carAvMAX").css('width', num + '%').show();
});
});
});
Any idea as to why it's going awry in Chrome would be hugely appreciated.
Thanks,
Lee.
your are passing 14.6 ( the mazda ) in your json and multiplying it by 10 for the width so thats why you are
out of bound of container change the logic of the calculation of the width and you will be fine. and the reason why in fire fox its ok and chrome not is because each browser parse the CSS differently . hope this helped

Javascript - onclick

first time posting here, but god know's I use this site to search for problems all the time :P Well, I'm having a problem of my own now that I can't seem to figure out easily searching around Google, and after playing with it for about 2 hours, I've finally decided to post a question and see what you guys think.
What I'm trying to accomplish here is to have a button that appears over a div when you hover over it that, when clicked, opens an editing pane. The button appears over the div correctly, but for some reason I cannot seem to make the onclick function work to save my life lol. Here's the code I'm working with. If it's not enough, please let me know and I'll add a little more sauce. :P
function place_widget(name, properties){
//bbox
var pleft = properties[0];
var ptop = properties[1];
var width = properties[2];
var height = properties[3];
var pright = pleft + width;
var pbottom = pleft + height;
var bbox = [pleft, ptop, pright, pbottom];
boxes[name] = bbox;
//ID's
var id = 'widget_' + name;
var editspanid = id + "_editspan";
var editbuttonid = id + "_editbutton";
var editpaneid = id + "_editpane";
//Creating Elements
var div = "<div id='" + id + "' class='widget' onmouseover='widget_hover(event);' onmouseout='widget_out(event);'>";
var editbutton = "<a id='" + editbuttonid + "' href='#'><img onclick='toggleEdit;' src='../images/edit_button.png'></a>";
var editspan = "<span id='" + editspanid + "' class='editspan'>" + editbutton + "</span>";
var editpane = "<span id='" + editpaneid + "' class='editpane'>:)</span>";
div += editspan + editpane + "</div>";
body.innerHTML += div;
//Configuring Elements
var editspanelement = document.getElementById(editspanid);
var editbuttonelement = document.getElementById(editbuttonid);
editbuttonelement.onclick = alert; //Does nothing.
var editpaneelement = document.getElementById(editpaneid);
var mainelement = document.getElementById('widget_' + name);
mainelement.style.left = (pleft + leftmost) + "px";
mainelement.style.top = (ptop + topmost) + "px";
mainelement.style.width = width;
mainelement.style.height = height;
getContentsAJAX(name);
}
Sorry for the ugly code :P Anyone have any idea why the onclick function isn't working?
Also, a bit of extra info: If I open up firebug and put in :
document.getElementById('widget_Text_01_editbutton').onclick = alert;
When I click the button, I get:
uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "native frame :: <unknown filename> :: <TOP_LEVEL> :: line 0" data: no]
I'm not exactly sure what that means off hand.
Thanks!
Can you try changing:
<img onclick='toggleEdit;' src='../images/edit_button.png'>
to:
<img onclick='toggleEdit();' src='../images/edit_button.png'>
Also, is "alert" a function you wrote?
Start by changing this:
editbuttonelement.onclick = alert; //Does nothing.
to this:
editbuttonelement.onclick = function() {alert("Got a click");};
and then change this:
var editbutton = "<a id='" + editbuttonid + "' href='#'><img onclick='toggleEdit;' src='../images/edit_button.png'></a>";
to this:
var editbutton = "<a id='" + editbuttonid + "' href='#'><img onclick='toggleEdit();' src='../images/edit_button.png'></a>";
What you are clicking on? The image or the link or the span? Do you know which is getting the click event?
document.getElementById('widget_Text_01_editbutton').onclick = alert;
causes illegal invocation because it is trying to set this to something else (the element) than window inside alert.
alert.call( {} )
//TypeError: Illegal invocation
alert.bind( window ).call( {} )
//works
So either:
document.getElementById('widget_Text_01_editbutton').onclick = alert.bind( window );
or even better as the above will only work in some browsers:
document.getElementById('widget_Text_01_editbutton').onclick = function(){alert();};
It will help you in executing.
<img onclick='toggleEdit;' src='../images/edit_button.png'>

Categories