I'm getting a weird error where in Internet Explorer 7, when I call Math.round on a float it gives me an "Invalid Argument" error. Consider the following:
var elementLeft = parseInt(element.style.left); // Here we're actually getting NaN
function Foo(x) {
this.x = x;
this.apply = function(element) {
element.style.left = Math.round(this.x) + 'px';
};
}
Foo(elementLeft);
In this case x is a non-negative number and element is just a DOM element in my page (a div, in fact).
Any ideas?
EDIT: The variable passed in as the x parameter is actually initialized earlier as parseInt(element.style.left). It appears that the first time I try to read element.style.left, IE is actually giving back NaN. I have updated the code to reflect this. Anyone know any workarounds for this?
It appears that the first time I try to read element.style.left, IE is actually giving back NaN.
The first time you read element.style.left, is there actually any left style set on the element? Remember element.style only reflects style properties set in the inline style="..." attribute and not those applied by stylesheets.
If you haven't set an inline style, style.left will give you the undefined object, which does indeed parseInt to NaN.
Is IE defaulting x to a bad value?
Scroll down to Item 10 on this page:
Everything was working fine in
Firefox, Google Chrome etal. But I was
having problems with IE (of all
flavours). No selection tool would be
presented and a javascript warning was
produced which told me about an
'Invalid argument' being submitted to
the Math.round function.
The cause was that when you first
click on the image to start your
selection, the scaleX and scaleY
variables in the javascript on the
page result in a value of Infinity.
Firefox and every other browser seems
to silently step over this and carry
on processing as normal. IE of course
did not.
The solution was to add the following
line after the initial scaleX and
scaleY variables are calculated. This
appears to have solved the problem
fully. if(scaleX == Infinity || scaleY
== Infinity) return false; I hope this helps someone else and saves them the
hour of hunting it cost me ;o)
I don't think it's Math.round() that's giving you the error. It's probably the CSS subsystem. Try an alert() on the value that you're getting.
Some frameworks such as jQuery have facilities to read the calculated position of elements -- without requiring you to have explicitly set CSS position properties on them. Try reading the position of your element through jQuery. It might work.
For some reasons Javascript only works for the inline styling.
For example
<div style="left:500px;"></div>
if you wish to work on the position of an element, try setting the initial position in Java Script file, example:
function Xyz() {
var elem = document.getElementById('id');
elem.style.left = 500px;
numberLeft = 500;
//Now you can manipulate the position
var increment= 50;
var newLeft = numberLeft + increment;
elem.style.left = newLeft + 'px';
}
You get the idea. Put your logic in.
Related
I'm inherited an HTML form that uses the js with() function:
with (document.images.myImage.style) {
left = x + "px";
top = y + "px";
visibility = "visible";
}
This code "moves" an image on a graph based on the left/top settings.
Movement is normal in Firefox, IE and Edge, but not in the others...I'm not familiar enough with js to recode so it works in all the browsers.
Does anyone have recomendations on how to recode this?
with is a statement, like a for loop, not a function. What with does is allow you to reference properties on an object without typing out the objects name every time.
with(myObj) {
x = y;
}
is the same as
myObj.x = myObj.y;
But it's not allowed in strict mode nor should it be used in non-strict mode (tends to be the source of a lot of bugs). So to translate any with code, just prefix any values coming from the object with the actual object.
document.images.myImage.style.left = x + 'px';
document.images.myImage.style.top = y + 'px';
document.images.myImage.style.visibility = 'visible';
with(expression) adds the expression to the scope search chain to the block inside the with statement.
The most direct replacement I can think of would be assigning a variable to document.images.myImage.style and prepending that to each line. So...
var style = document.images.myImage.style;
style.left = x + "px";
style.top = y + "px";
style.visibility = "visible";
Thank you for all the information.
What I ended up doing is as "Mike C" suggested and replaced the with() statement using "document.images.style.xxx=" statements.
So far it works find in all the browsers I could find.
Again, the forum is amazing at letting you on to what others know/have discovered...Thanks again for all your help.
I'm working on a jQuery function to set the height of a div based on the height of the window and some other elements, and I noticed something strange. The outerHeight() function seems to accept an integer parameter, even though the documentation doesn't specify that one is allowed.
So this seems to work in both Chrome and Firefox:
var o_height = $("#content").outerHeight();
var n_height = $(window).outerHeight() - $("#nav").outerHeight();
if (n_height > o_height) {
$("#content").outerHeight(n_height);
}
The alternative is to calculate the padding and then subtract it, which is a few lines longer:
var o_height = $("#content").outerHeight();
var n_height = $(window).outerHeight() - $("#nav").outerHeight();
if (n_height > o_height) {
var padding = $("#content").outerHeight() - $("#content").height();
$("#content").height(n_height - padding);
}
What I'm wondering is whether it's safe to use the shorter version. I'll be doing stuff like this several times, so I'd rather cut down on the length of the script, but not at the cost of stability. Is this a stable, but undocumented feature, or do I just need to accept the extra weight in the function?
In case anybody else stumbles upon this, it appears that this functionality was actually added all the way back in 1.8.0 for both outerHeight and outerWidth, but that despite frequent reports, the documentation still hasn't been updated.
can anyone help please, there seems to be many terms for what im looking for but still unable to fatham the answer?
Im using javascript to to get the window height then subtract 40 px to give me the value of the rest of the available space, but it gives me 'invalid argument' and im not sure why
var WH=$(window).height();
var TopSpace=40;
var AvailSpace=WH-TopSpace;
document.getElementById("BottomSpace").style.height=AvailSpace;
When the page loads fresh, it shows an Invalid Argument, if i press F5 it does the job??
Many thanks
if you are using jquery to get the window height, why not use it go change the style of the "BottomSpace"? I tested your code, and the problem (at least in Safari) is that you don't set the units in the height, so either use jQuery for it, or set the unit (px). Here is the jsFiddle.
var WH=$(window).height();
var TopSpace=40;
var AvailSpace=WH-TopSpace;
//$("#BottomSpace").height(AvailSpace);
document.getElementById("BottomSpace").style.height=AvailSpace + "px";
I have several fixed position divs with the same class at varying distances from the left edge of the window, and I'd like to increase/decrease that distance by an equal amount on each div when a certain action happens (in this case, the window being resized). I've tried positioning them with CSS and percentages rather than pixels, but it doesn't quite do the job.
Is there a way to store the position of each of those divs in an array and then add/subtract a given amount of pixels?
Here's what I've tried so far - I'm still getting my head around JS so this could be really bad for all I know, but here goes:
roomObjects = $('.object-pos');
var objectCount = 0;
for ( var objectCount = 0; objectCount < 10; objectCount++;) {
roomObjects = rooomObjects[objectCount];
console.log(roomObjects.css("background-position").split(" "));
}
Do you mind sharing why percentages wouldn't work? Usually that's what I would recommend if you're wanting the page to scale correctly on window resizes. I guess if you really wanted to you could do something like:
$(window).resize(function() {
$('#whateverdiv').style.whateverproperty = $('#whateverdiv').style.whateverproperty.toString() + (newPosition - oldPosition);
oldPosition = newPosition;
}
this is obviously not the complete code, but you should be able to fill in the blanks. You'll have to set the oldPosition variable on page load with the original position so that the function works the first time.
edit: you'll also have to strip off the units from the x.style.property string, so that you'll be able to add the value to it
A problem you might well be facing is that when retrieving the current left or top properties, they are returned as a string, with px of % on the end. Try running a parseInt() on the returned values to get a number, then you might well be able to add to the values. Just be sure, when reassigning, that you concatenate "px" or "%" on the end as appropriate.
You could use a bit of jQuery :
var el = $("#id");
var top = el.css("top");
el.css("top", top * 1.2); // increase top by 20%
saves mucking around in the DOM
This might be useful if you want to position things relatively: http://docs.jquery.com/UI/Position
I'm trying to get the value of an inherited CSS property using Javascript. I haven't been able to find a comprehensive answer.
Example CSS:
div {
width: 80%;
}
Example Markup:
<div id="mydiv"> Some text </div>
Using javascript (jQuery, or native), I need to get the width of the element-- not in pixels, but the string "80%".
$('#mydiv').css('width'); // returns in px
$('#mydiv')[0].style.width // empty string
getComputedStyle($('#mydiv')[0]).width // returns in px
The reason I need the value as a string is because I need to copy the style to another element. If it's declared as a percent, the other value needs to be a percent. If it's declared in px, the other value needs to be in px.
The real trick is that this property could be inherited, not declared explicitly on the element (as in my example).
Does anyone have any ideas?
What you are searching for is this quirksmode.org article. It proposes the function
function getStyle(el, styleProp) {
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
Still, you should read that article carefully. They names of the styleProps are not really cross-browser, and you will see how different browsers handle this. Opera seems to have the best support for reporting the correct values.
There's no way to get the percentage value I'm afraid. You can try something like this:
var widthpx = getComputedStyle($('#mydiv')[0]).width;
var parentWidth = $('#mydiv').parent().css('width')
var width = ( 100 * parseFloat(widthpx) / parseFloat(parentWidth) ) + '%';
get the offSetWidth of the element, and the offsetWidth of its offsetParent, and calculate the percentage from the two integers.
This binds an event handler to an element for the click event and alerts the element's relative width compared to it's parent element.
$('#mydiv').on('click', function () {
//element width divided by parent width times 100 to make a percentage
alert(Math.round($(this).width() / $(this).parent().width() * 100) + '%');
});
Here is a demo: http://jsfiddle.net/X67p5/