I’m working on some native JavaScript (not my forte.. at all) and am not seeing the result of my function. I’m sure I’ve got a syntax error in here somewhere. Can you help me identify it? FYI- The function will dynamically center an object on the page.
this.style[left]= ((windowWidth - this.style[width])/2);
this.style[top]= ((windowHeight - this.style[height])/2);
You have, at least, three problems.
First: The CSS
height,width,leftandtopproperties take lengths. You are passing them Numbers.You must include a unit.
Likewise, you need to account for the unit on the values for the width and height.
Second: You also need to balance your parentheses.
Third: When using square bracket notation, you need to pass in strings. At the moment, I assume that
leftandtopareundefined.Finally, this will only work if the element has its width and height defined using inline style (or if those properties have been set via JavaScript). Otherwise the values you are trying to read will be
undefined. In this case you will need to deal with the computed style.Also remember that
topandleftwill have no effect unless the element is positioned.