Javascript: Change value of x while x is object.style.left; - javascript

here is my situation:
I have a div with a CSS position of `"left:10px;"
All divs position's are set to fixed.
Now I put this value into a variable (JS):
var Left = document.getElementById("div").style.left;
Now I can alert it: alert(Left); and I get a box witch says "10px"
Here is the fiddle for it: http://jsfiddle.net/L19rq2tk/2/
Now I want to change the value of the position by using the variable Left. I tried every possibility that came to my mind:
Left = "100px"; -->does not work
Left = 100px; -->does not work
Left = "100"; -->does not work
Left = 100; -->does not work
Changing the position by the following code works:
document.getElementById("div").style.left="100px";
Would be glad if anyone could help me!

left works with position:absolute
Here is updated fiddle
Updated
By adding position weather relative or absolute will do the job. By adding position:absoute could have side effects on your design(as lonic mentioned in comment)
DEMO

You must use the explicit form that you mentioned at the end of your answer document.getElementById("div").style.left="100px";. If you are trying to avoid looking up the element each time, you should be able to do something like:
var savedStyle = document.getElementById("div").style;
savedStyle.left = '100px';
You can't set the value they way you are trying to because Left stores a copy of the value, it doesn't point to the same value. When you set Left to a new value you are only changing the value it is storing, not the value that object.style.left is storing. While you can have multiple variables point to the same object, you can't have multiple variables point to the same value. I've included a demo snippet showing the difference.
var x = 1;
var y = x;
document.write('x = ' + x + '<br>');
document.write('y = ' + y + '<br>');
document.write('Setting y to 2<br>');
y = 2;
document.write('x is now = ' + x + '<br>');
document.write('y is now = ' + y + '<br>');
var xObj = { myValue: 3 };
var yObj = xObj;
document.write('xObj.myValue = ' + xObj.myValue + '<br>');
document.write('yObj.myValue = ' + yObj.myValue + '<br>');
document.write('Setting yObj.myValue to 1<br>');
yObj.myValue = 1;
document.write('xObj.myValue is now = ' + xObj.myValue + '<br>');
document.write('yObj.myValue is now = ' + yObj.myValue + '<br>');

See this fiddle.
You've assigned the 100px, but you haven't add position:relative or position:absolute. Due to this fact you haven't seen anything, but it was assigned in the background.

by assigning the value to the variable left nothing will be done.
you need to assign the value to the html element.
use
document.getElementById("div").style.left="100px";
left is a var which only holds the prev value.
you also need to give
positon:relative
to your div else it wont move, left, top and other position css can only be applied if the element has some position property which was missing in your.
http://jsfiddle.net/L19rq2tk/
here is your updated fiddle;

Related

Moving a div to the right

I have this really fundamental question, but I have no idea wheres the problem.
Here's fiddle: http://jsfiddle.net/nL6fvrz8/
I just simply want to move the object to the right with this js, but when I do that in the fiddle it doesnt move at all and if I do it on my computer, it keeps giving me the primary position of the 200px(the amount i want to add it to its first position)
function doMove(){
var foo = document.getElementById("foo");
foo.style.left = (foo.style.left + 200) + 'px';
}
I know its prolly a little simple, but im clueless. Thanks for your help.
Only inline styles can be referenced via the x.style syntax. To get styles set via a style sheet, use getComputedStyle:
function doMove() {
var elem = document.getElementById("foo");
var foo = window.getComputedStyle(elem, null).getPropertyValue("left");
elem.style.left = parseInt(foo,10) + 200 + 'px';
}
jsFiddle example
Define basic position in JS as well, and add parseInt when reading style (left is string in format like this 200px).
document.getElementById("foo").style.left = "300px";
function doMove() {
var foo = document.getElementById("foo");
foo.style.left = (parseInt(foo.style.left) + 200) + 'px';
}

getElementsByName which name?

I'm creating a bunch of divs in javascript, and at a certain time I wish to delete all the divs.
My code is like this:
function CreateDiv(width, height, row, col){
var thisTile = document.createElement("div");
thisTile.style.position = "absolute";
thisTile.style.width = width + "px";
thisTile.style.height = height + "px";
thisTile.style.top = row*TileH + topMargin + "px";
thisTile.style.left = col*TileW + leftMargin +"px";
thisTile.style.backgroundImage = "url(" + imagePath + ")";
thisTile.style.backgroundSize = imageWidth + "px " + imageHeight +"px";
thisTile.style.backgroundRepeat = "noRepeat";
thisTile.style.backgroundPosition = "-" + col*TileW + "px -" + row*TileH + "px";
thisTile.onclick = TileClicked;
thisTile.name = "tiles";
document.body.appendChild(thisTile);
return thisTile;
}
...
var tmp = document.getElementsByName("tiles");
alert("tmp length: " + tmp.length);
for (var i = 0; i < tmp.length; i++)
document.body.removeChild(tmp[i]);
but every time tmp is an empty array, so I can't actually remove the divs I want to,
I tried to change
tile.name = "tiles"
to
tile.nodeName = "tiles"
or
tile.className = "tiles"
but none of them worked, I just wonder which name attribute or property of an element exactly is the one in getElementsByName?
The getElementsByName method returns a list of elements with an attribute called name, with the given value, but only for those elements in which such an attribute is allowed by HTML specifications. And div is not among them.
In reality, it’s a bit more complicated. Modern browsers (including IE 10) actually implement it so that all elements with the name attribute in HTML markup are considered, even if the markup is invalid by HTML specs, like <div name=tiles>foo</div>. But not elements that just have the name property assigned to them in JavaScript. The difference is that the markup attribute also causes the information to be added into the attributes object.
So if you really, really wanted to use name here (you shouldn’t), you could replace
tile.name = "tiles"
by
thisTile.setAttribute("name", "tiles");
And it still wouldn’t work on IE 9 and older.
From the description of the purpose in the question, it seems that you should just collect an array of elements that you have added, if you later need to remove them. That is, in addition to adding an element in the document, you would append it to an array that you create, and then, when you need to delete them all, you just traverse the array.
Actually DIV tag does not have name attribute.
check the following reference:
http://www.w3schools.com/tags/tag_div.asp
give your divs a specific class and access then using :
elements = document.getElementsByClassName(className)
Here in your code you have used the following codes including tiles-
thisTile.name = "tiles";
and
var tmp = document.getElementsByName("tiles");
But you have to use tiles[] in place of tiles to make tiles an array of elements.
That is the only mistake in your code. your code will run fine if you change these two statements.

Using JavaScript to increment top/left/bottom/right values

I am trying to increment the position of an element by, say, x pixels. Here is what I've tried so far:
var top = document.getElementById("something").style.top;
top = top + "300px"
I know that this is not going to work, but I was wondering if it was possible to increment a position value like this.
Because style.top is a string with units on the end of it like "300px" you can only do math with it when you convert just the numeric part to an actual number.
Assuming you have a positioned element (so setting the top value will do something) and you already have a top style set directly on the element and not set via CSS (so getting obj.style.top will actually get you something), you can do it by parsing the number out of the style value like this:
var obj = document.getElementById("something");
var topVal = parseInt(obj.style.top, 10);
obj.style.top = (topVal + 300) + "px";
Working example: http://jsfiddle.net/jfriend00/pt46X/
That won't work fine because, for example, if top had a value of 200px, it would become "200px300px". Try this:
var elem = document.getElementById("something");
elem.style.top = parseInt(elem.style.top, 10) + 300 + "px"
Demo WEEEE!!!!
let top = 0;
let left = 0;
let text = document.getElementById("TextToTranslate");
text.setAttribute("style","top:"+top+"px; "+left+":px;");
use this in a while loop and it works fine, i'm just figuring out how to slow it down so i can see the transition

Javascript style.left is empty string

next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction] is: " ". So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left supposed to return an integer?
Why would this be?
Presumably because it hasn't been set to anything.
Isn't style.left supposed to return an integer?
No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).
See How to get computed style of a HTMLElement if you want to get the computed value for the property rather than what I described in the previous paragraph.
style provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle instead.
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
var lft = document.defaultView.getComputedStyle(el)[direction];
pos = parseFloat(lft);
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
Note: like Elliot said you'll have to get the currentStyle/computedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.
Just a comment.
In your code:
> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;
The split in the first line is superfluous, in the second line parseInt will convert (say) 10px to the number 10 just as effectively (and more efficiently) than what you have.
pos = parseInt(el.style[direction], 10);

Check whether variables are equal with jquery

Hey i am new to jquery and i was wondering whether someone could give me some help when it comes to working with variables. The below is what i have thus far. I want to find a certain divs left position and width and then do some basic maths with those variables. Sorry is this explanation is a little confusing. So just a example as to how i would create a variable from a divs width and how to check whether variables are equal to one another would be great.
$(document).ready(function(){
//Check distance from left
var p = $(".GalleryItem");
var position = p.position();
$(".LeftPosition").text( "left: " + position.left + ", top: " + position.top );
//Check width of GalleryItem
var GalleryContainer = $(".GalleryItem");
$(".WidthText").text( "innerWidth:" + GalleryContainer.innerWidth() );
//Check width of Gallery
var GalleryContainer = $("#Gallery");
$(".WidthGalleryText").text( "innerWidth:" + GalleryContainer.innerWidth() );
});
The .width() function is "recommended when width needs to be used in a mathematical calculation". It also covers windows and document rather than just divs.
var position = $('.GalleryItem').position();
var galleryItemLeft = position.left;
var galleryItemWidth = $('.GalleryItem').width();
var galleryWidth = $('#Gallery').width();
// do calculations such as
var galleryItemRight = galleryItemLeft + galleryItemWidth;
// check if one width = another
if(galleryItemWidth == galleryWidth) { ... }
For jQuery, working with return values is just like working with any return value in javascript. Set a var = to the function (expecting a return value), compare with the '==' operator. In jQuery you can also set the actual selector objects to variables as you have done with 'var p = $('.GalleryItem');' To compare selector objects you would compare them by their properties, such as position, width, color, etc.
Hope this helps.
I guess you could just do something like:
var galleryItemWidth = $(".GalleryItem").innerWidth();
var galleryWidth = $("#Gallery").innerWidth();
And then just check something like this:
if (galleryItemWidth == galleryWidth) {
// Do something
}
else {
// Do something else
}
Or maybe I misunderstood your question?

Categories

Resources