Positioning floating element using JavaScript (for animation) - javascript

I want to make floating HTML5 element move back and forward on my page. Exactly like SmoothDivScrolling that is already out there. I did try SmoothDivScrolling and it is not working well with the layout of my page.
So I have started to write my own.
If I give a position to my element using CSS I will be able to retrieve the position with:
element = document.getElementById(image);
position = element.style.left;
// removing px from the value
position = parseInt(position.substring(0,position.length-2));
This will return the left position of the element inside its parent only if the CSS contain:
left:0px;
As mentioned, I want my elements to be floating because I plan to have many more than one element;
Now since I want to animate my element I have to change the position by changing the value of 0px with:
fish.style.left = (newPosition)+'px';
It is working if I provide the style of my floating element with:
position:relative; //This doesnt really afect my floating
left:0px; //this does
So I tried to retrieve the position with DOM instead of CSS using:
var element = document.getElementById(image);
var rect = element.getBoundingClientRect();
position = rect.left;
Now this is working. It retrieves the position of the element relative to the body even if no left positioning was specified in the style.
I am wondering if there is way to change the position of that element without going trough CSS style. Because each element might have different width, floating them take care of the positioning. If I provide a position to each of them they won't be floating anymore.
The floating option avoid all the math involved on positioning. But if it's really needed I guess I will do the math.
Any suggestions?
Here is the full code for who ever wants to reinvent the wheel with me
<body style="margin:0px;">
<div id="scroller" style="position:absolute;left:400px;width:800px;border:1px solid #000000;overflow:hidden;height:auto;">
<div id="scrollWrap" style="margin:0px;position:relative;width:400px;margin:auto;border:1px solid #000000;overflow:hidden;height:150px;">
<figure id="shark" style="float:left;margin:0px;padding:0px;width:150px;display:inline-block;">
<img id="image" src="shark.jpeg" alt="The Shark" style="border:1px solid #000000;position:relative;left:0px;width:150px;height:150px;">
</figure>
</div>
</div>
<script type="text/javascript">
setInterval(function(){ do_move("shark"); }, 10);
</script>
</body>
<script type="text/javascript">
var frameDirection;
function do_move(image) {
var container = document.getElementById("scrollWrap");
var bodyRect = container.getBoundingClientRect();
var element = document.getElementById(image);
var rect = element.getBoundingClientRect();
offset = rect.left - bodyRect.left;
fish = document.getElementById(image);
horz = fish.style.left;
fishSize = document.getElementById(image).offsetWidth;
horz = parseInt(horz.substring(0,horz.length-2));
var frameWidth = document.getElementById('scroller').offsetWidth;
var wrapWidth = document.getElementById('scrollWrap').offsetWidth;
var nbrImg = document.getElementById("scrollWrap").getElementsByTagName("figure").length;
if (horz==0) {
frameDirection='right';
}
else if (horz == (wrapWidth-fishSize)) {
frameDirection='left';
}
if (horz<=wrapWidth && frameDirection == 'right') {
horz += 1;
fish.style.left = (horz)+'px';
}
else if (horz<=wrapWidth && frameDirection == 'left') {
horz -= 1;
fish.style.left = (horz)+'px';
}
}
</script>

If I understand correctly, you want to initially float your elements, then switch to absolute positioning, but keep everything in the same place, so you can animate them?
If so, this code may help you. It's not based on your html, just an example.
// get all the floating elements
var floaters = document.getElementsByClassName("floater"),
index, floater, rect;
// go over them backwards
for (index=floaters.length-1; index>=0; index--) {
floater = floaters[index];
// get current position
rect = floater.getBoundingClientRect();
// convert it to style
floater.style.left = rect.left + "px";
floater.style.top = rect.top + "px";
// switch to absolute positioning
floater.style.position = "absolute";
floater.style.float = "none";
}
I made a little jsfiddle, so you can test it.

Related

Position image randomly after each onclick event (image must be in div tag)

So I am very new (as I am sure my code shows :P) and I must create code that contains an image in a div tag. It must be this way. Once the document is opened the image(div) is to be displayed at a random position. Each time the image(div) is clicked, the image alone moves to another random position. It does not replicate itself. Just moves. I have had other "better" attempts but with all my editing and changing all I get is the image in the top left corner.
I tried numerous things that all failed to work. Obviously failed because the code was terrible.
I have tried a variation of onclick events etc...I know many errors are visible. This is not one of those instances where I believe the logic is sound and it should work. This is a "what am I at" instance
<script>
function fpos () {
var img = document.getElementById('myImage') //is this needed at all?
var x = Math.floor(Math.random()*600);
var y = Math.floor(Math.random()*600);
var z = Math.floor(Math.random()*600);
}
function rmove() {
img.style.top = x + 'px';
img.style.left = y + 'px';
}
</script>
</head>
<body onload="fpos">
<div style = position:absolute; onclick="rmove" >
<img id="myImage" src='images/iasip.jpeg'> </img>
</div>
</body>
So, first, don't take this the wrong way my man but you gotta post some code to show us what you're working with. Makes all the difference for troubleshooting.
That said, you're gonna need to do with with JS. First target the image element. Can use querySelector to hit either the class or id or just getElementById.
Then add an event listener to render it at a random coordinate. Like this.
<div id="imageContainer">
<img src="your-image-source" alt="your-image-description">
</div>
<script>
// get the image container element
var imageContainer = document.getElementById("imageContainer");
// set the initial random position for the image container
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
// when the image container is clicked, set a new random position
imageContainer.addEventListener("click", function() {
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
});
</script>
Can either do that inline like in the example or add it to your script file.
Here is a working example I just threw together.
Basically you need to create a function that moves the image each time by calculating a random number for the height and width and then multiplying by the size of the window so that number can span the full width/length of the screen.
Then you can add 'px' to the end of the calculation to use pixels as the unit and set that to the left and top properties of the image to move it that far from the left and top of the screen using absolute position (coordinates).
window.onload = function() {
move()
}
function move() {
let img = document.getElementById('logo')
img.style.left = Math.floor(Math.random() * window.innerWidth) + "px"
img.style.top = Math.floor(Math.random() * window.innerHeight) + "px"
}
#logo {
height: 100px;
position: absolute;
}
<div>
<img onclick='move()' id='logo' src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/LEGO_logo.svg/2048px-LEGO_logo.svg.png' />
</div>
Don't worry, try to isolate some code so we can review it.
Once the document is opened the image(div) is to be displayed at a
random position.
By inspecting an element's properties with Right Click > Inspect > Property you'll find all javascript properties that you have access to once you select the element with a selector (document.querySelector for example)
Try something with that, i think that the easiest way is to use
element.style.transform = "translate(x,y)"
like x.style.transform = "translate(10px, 20px)";

Javascript get absolute position of a div

I have a div (oCell) created at runtime using javascript.
I then want to position another independant div (random-div) relative to this div. For reasons within the program random-div has to be positioned absolutely and oCell relatively. The oCell div is positioned relative as it is within a table.
My problem is I need to find the absolute position of the oCell div, rather than the relative position.
So far I have:
var oCell = document.createElement("td");
var height = oCell.getBoundingClientRect().top;
var right = oCell.getBoundingClientRect().right;
oCell.oBoxPositionTop = height;
oCell.oBoxPositionSide = right;
But from what I can understand, this is returning the relative height of oCell div, which is in turn not positioning random-div in the correct place.
The getBoundingClientRect gives coordinates in viewport coordinates (or coordinates relative to the visible content shown in your browser window). With absolute positioning, you need document coordinates. To convert viewport coordinates to document coordinates, add the scroll offsets of the page to the left and top values returned by getBoundingClientRect:
//technique used in JavaScript: Definitive Guide
var scrollOffsets = (function () {
var w = window;
// This works for all browsers except IE versions 8 and before
if (w.pageXOffset != null) return {x: w.pageXOffset, y:w.pageYOffset};
// For IE (or any browser) in Standards mode
var d = w.document;
if (document.compatMode == "CSS1Compat")
return {x:d.documentElement.scrollLeft, y:d.documentElement.scrollTop};
// For browsers in Quirks mode
return { x: d.body.scrollLeft, y: d.body.scrollTop };
}());
//Your code:
var oCell = document.createElement("td");
//changed from height to top and gets document coordinates of position
var top = oCell.getBoundingClientRect().top + scrollOffsets.y;
//changed from right to left
var left = oCell.getBoundingClientRect().left + scrollOffsets.x;
oCell.oBoxPositionTop = top;
oCell.oBoxPositionSide = left;

How to get the real scroll height of div (say, inner text size)

I'm trying to make a auto-scrolling div that go to its top when it reaches the end. But it doesn't work...
function scrollPannel()
{
var pannel = document.getElementById('pannel');
if (typeof scrollPannel.count == 'undefined')
{
scrollPannel.count = 0;
}
else
{
scrollPannel.count += 2;
}
// trouble is here
if ((scrollPannel.count - pannel.scrollHeight) > pannel.clientHeight)
{
scrollPannel.count = 0;
}
pannel.scrollTop = scrollPannel.count;
setTimeout('scrollPannel()', 500);
}
HTML:
<div id='pannel' style="height:200px;overflow:auto" onmouseover="sleepScroll()">
<p>...</p><!-- long text -->
</div>
And after, I will need to find how to stop scrolling when "onmouseover" occures.
EDIT: I did not explained the problem clearly. In fact, I have tried something like:
if (scrollPannel.count > pannel.scrollHeight)
{
scrollPannel.count = 0;
}
The problem is that scrollHeight seems greater than div inner text. So it makes a lot of time to return to the top.
So I need an element property of which I could use the value to compare with my count variable. However I don't know Javascript a lot and I could not find anything. I hope it is as well simple as I think of it.
Try:
// calculate max scroll top position (go back to top once reached)
var maxScrollPosition = element.scrollHeight - element.clientHeight;
// example
element.scrollTop = maxScrollPosition;
That should do what you need.
You could try using the scrollHeight property.
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollHeight
The solution I have involves jQuery, hope that's not a problem.
JavaScript:
var timeout;
function scrollPannel()
{
var divHeight = $("#pannel").height() / 2;
var scrollCount = $("#pannel").scrollTop();
var scrollHeight = $("#inside").height() - 20 - divHeight;
scrollCount += 2;
if ((scrollCount - scrollHeight) > 0)
{
scrollCount = 0;
}
$("#pannel").scrollTop(scrollCount);
timeout = window.setTimeout(scrollPannel(), 100);
}
function scrollStop() {
window.clearTimeout(timeout);
}
HTML:
<div id='pannel' onmouseover="scrollStop();" onmouseout="scrollPannel();">
<p id="inside"></p><!-- long text -->
</div>
Explanation:
jQuery's .height() of the inside element <p> gives us the actual height you're looking for, but it's not enough for reaching the bottom, since that happens before we reach the element's height. A little investigation shows that the "top" of scrollTop() is about half way inside the original div's height. You may need to play around with divHeight to get the exact results you're looking for.
Of course, I also included a method for stopping and continuing scrolling.
Good luck!
You should use scrollHeight property but to call it, you need to use an index like that:
$('#pannel')[0].scrollHeight;
If you set the scrollTop and scrollLeft to really high silly values they only ever get set as their maximum allowed values which I think is what you need? You can then use them to work out the scroll center if you wished.
See snippet example.
var mB = document.getElementById('myBox');
var mR = document.getElementById('myResult');
// Set the top and the left to silly values
mB.scrollTop = 99999999;
mB.scrollLeft = 99999999;
// They will only end up being set as their max
mR.innerHTML = "maxTop="+mB.scrollTop+"<br>maxLeft="+mB.scrollLeft;
// Now take the max values and divide by 2 to scroll back to middle.
mB.scrollTop = mB.scrollTop/2;
mB.scrollLeft = mB.scrollLeft/2;
#myBox{
overflow:auto;
}
#myContent{
border:1px solid black;
background-color:red;
}
<div id='myBox' style='width:300px;height:300px'>
<div id='myContent' style='width:500px;height:800px;line-height:800px;'><center>I am the center of the content</center></div>
</div>
<div id='myResult'></div>
I have got one solution....
function findMaxReach(){
let maxReach =0
document.querySelector('.YourElement').scrollLeft = 100000;
maxReach = document.querySelector('.YourElement').scrollLeft;
document.querySelector('.YourElement').scrollLeft = 0;
return maxReach
}

how do i get the x and y position directly under the left bottom side of the input rectangle?

I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>

Get position of map area(html)?

Is this possible? I'm trying to find the x and y coordinates of the element in relation to the browser.
var position = $(this).position();
x = position.left;
y = position.right;
Doesn't work.
Is there any way to do this?
http://adamsaewitz.com/housing/
highlight the blue room 070
The problem lies in the fact that you are accessing the top/left of an area element.
The area element is not positioned where its coords say. This is handled behind the scenes by the dom/browser.
So you need to find the image that the area relates to and grab its offset.
var imgId = $(this).closest('map').attr('name');
var imgPos = $('#' + imgId).offset();
Then, you grab the coords attribute of the area and split it to get left/top/width and use those to pinpoint the location inside the image.
var coords = $(this).attr('coords').split(',');
var box = {
left: parseInt(coords[0],10),
top: parseInt(coords[1],10),
width: parseInt(coords[2],10)-parseInt(coords[0],10),
height: parseInt(coords[3],10)-parseInt(coords[1],10)
};
Take into consideration the width/height of the info box that appears (and since you animate it, take that into consideration as well) and you get to
x = imgPos.left + box.left + box.width/2 - 65; // 65 is the info width/2
y = imgPos.top + box.top -20 -160 -1; // 20 is the animation, 160 is the info height, 1 is a safe distance from the top
demo: http://www.jsfiddle.net/XBjwN/
Edit for updated question: Since you're using <area> it's a different story, and fetching from the coords attribute is much easier, like this:
var position = $(this).attr('coords').split(',');
x = +position[0] - 50;
y = +position[1] - 170;
The offsets are just to account for the hard-coded width/height of the tooltip itself. In addition to the above, you want to use top and left rather than margin-top and margin-left. Also to account for the #content <div>'s position in the page, give it a relative position for the tooltip to sit in, like this:
#content { position: relative; }
Then...instead of .after(), use .append() so it gets added inside that parent.
You can test the result here.
For original question:
The object .position() returns has top and left properties...but you want .offset() here anyway (it's relative to the document, where .position() is relative to the offset parent), so it should look like this:
var position = $(this).offset(),
x = position.left,
y = position.top; //not right!
Or this:
var position = $(this).offset();
var x = position.left;
var y = position.top;
...but without a single var comma-separated statement, or a var on each line, you're also creating (or trying to) global variables, which will blow up in IE.
$(document).ready(function () {
$('map').imageMapResize();
$('area').hover(function () {
$('.imgpopover').css({ "display": "block", "top": $(this).attr("coords").split(',')[1]+"px", "left": $(this).attr("coords").split(',')[0]+"px" })
$('.imgpopover label').text($(this).attr("title"))
}, )
});

Categories

Resources