How to detect if an element is covered/overlapped by another one? - javascript

I have a problem that I want to detect if an element is covered by another one in one page.
eg:
DOM elements
<div class="ele ele1"><p>A</p></div>
<div class="ele ele2"><p>B</p></div>
<div class="ele ele3"><p>C</p></div>
<div class="cover"><p>D</p></div>
CSS style
.ele{
display: inline-block;
width: 100px;
height: 100px;
position: relative;
}
p{
width: 100%;
text-align: center;
}
.ele1{
background-color: red;
}
.ele2{
background-color: blue;
}
.ele3{
background-color: green;
}
.cover{
position: absolute;
width: 100px;
height: 100px;
left: 300px;
top: 10px;
background: grey;
}
http://jsfiddle.net/veraWei/6v89b1fy/
How to detect element A is not been covered but element C is covered by ele D?
One more thing: the number of "D" is uncertain. Maybe there are E/F/G... in the page.
I appreciate all the thoughts or existing examples/jQuery plugins/CSS/etc.
Thanks all your guys' detailed answers. But I need more shortly explanation maybe one attribute that indicate that A is not covered by any elements and C is covered by rendering. Is there any plugin or attribute existing?

Why not try the following :
1) Find the element position relative to the viewport:
rect=elt.getBoundingClientRect();
x=rect.left;
y=rect.top;
(or may be consider the midpoints coordinates)
2) Find the top element at position x, y:
topElt=document.elementFromPoint(x,y);
3) Check if the top element is the same than the original element :
if(elt.isSameNode(topElt)) console.log('no overlapping');

Are you looking for something like this?
http://jsfiddle.net/6v89b1fy/4/
var coverElem = $(".cover");
var elemArray = [];
elemArray.push($(".ele1"), $(".ele2"), $(".ele3"));
for(i=0; i< elemArray.length; i++)
{
var currElemOffset = elemArray[i].offset();
var currElemWidth = elemArray[i].width();
var currElemStPoint = currElemOffset.left ;
var currElemEndPoint = currElemStPoint + currElemWidth;
if(currElemStPoint <= coverElem.offset().left && coverElem.offset().left <= currElemEndPoint)
{
elemArray[i].append("<span>Covered</span>");
}
else
{
elemArray[i].append("<span>Not covered</span>");
}
}

Here is a quick example of how you may go about doing it. This would check for both vertical and horizontal overlapping. This is kind of generic and not-so-generic as well since this is based off the HTML in your question. Adjust the top/left values of the .cover to see it work for all possible cases.
var $cover = $(".cover"),
cWidth = $cover.width(),
cHeight = $cover.height(),
cLeft = $cover.offset().left,
cRight = $(window).width() - (cLeft + cWidth),
cTop = $cover.offset().top,
cBtm = $(window).height() - (cTop + cHeight);
$("div:not(.cover)").each(function() {
var $this = $(this),
eleWidth = $this.width(),
eleHeight = $this.height(),
eleLeft = $this.offset().left,
eleTop = $this.offset().top,
eleRight = $(window).width() - (eleLeft + eleWidth),
eleBtm = $(window).height() - (eleTop + eleHeight);
if (
cLeft < (eleLeft + eleWidth) &&
cRight < (eleRight + eleWidth) &&
cTop < (eleTop + eleHeight) &&
cBtm < (eleBtm + eleHeight)
) {
alert($this.text() + " is covered by " + $cover.text());
}
});
.ele {
display: inline-block;
width: 100px;
height: 100px;
position: relative;
margin-top: 40px;
}
p {
width: 100%;
text-align: center;
}
.ele1 {
background-color: red;
}
.ele2 {
background-color: blue;
}
.ele3 {
background-color: green;
}
.cover {
position: absolute;
width: 100px;
height: 100px;
left: 60px;
top: 110px;
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ele ele1">
<p>A</p>
</div>
<div class="ele ele2">
<p>B</p>
</div>
<div class="ele ele3">
<p>C</p>
</div>
<div class="ele ele3">
<p>D</p>
</div>
<div class="ele ele3">
<p>E</p>
</div>
<div class="ele ele3">
<p>F</p>
</div>
<div class="ele ele3">
<p>G</p>
</div>
<div class="cover">
<p>COVER</p>
</div>

OK. I've gone through all cases of overlapping and have created this fiddle. I've used getBoundintClientRect() and have used it to get top, left, bottom, right values of two divs on which overlapping is to be checked and then I've compared the offsets using various conditional statements and conditions too which you'll find below. In the fiddle all your four elements are having position: absolute, adjust their top and left values to make them overlap one another and to check whether two elements are overlapping or not? pass the two elements in the function -
checkElements(elA, elB); // pass two elements to check
which is in the very last.
You will see the long if else conditions in the fiddle, they are just for testing all possibilities of overlapping. Here is that all possible conditions used to check overlapping -
if((eleB.top >= eleA.top && eleB.top <= eleA.bottom) || (eleB.bottom >= eleA.top && eleB.bottom <= eleA.bottom)) {
if((eleB.left >= eleA.left && eleB.left <= eleA.right) || (eleB.right >= eleA.left && eleB.right <= eleA.right)) {
el1.innerHTML = '<p>covered</p>';
}
else {
el1.innerHTML = '<p>not covered</p>';
}
}
else {
el1.innerHTML = '<p>not covered</p>';
}
You will also see if B overlaps A then it will write A is covered because I've compared using x and y coordinates of A and B. In this case, I think an additional condition checking z-index will be used. I've not created for that.
Check the fiddle, and adjust top and left values of different elements and then pass two elements in the function checkElements() and see the result is correct or not.
You can also do all the checking simultaneously as -
checkElements(elA, elB); // check if A is overlapped by B
checkElements(elB, elC); // check if B is overlapped by C
checkElements(elC, elD); // check if C is overlapped by D
See this fiddle using the multiple checking.
EDIT: If looping is the problem, then you can combine all the loops of if else into a single if else like this -
if(((eleB.top >= eleA.top && eleB.top <= eleA.bottom) || (eleB.bottom >= eleA.top && eleB.bottom <= eleA.bottom)) && ((eleB.left >= eleA.left && eleB.left <= eleA.right) || (eleB.right >= eleA.left && eleB.right <= eleA.right))) {
el1.innerHTML = '<p>covered</p>'; // or your code of adding true to the attribute that tells about overlapping
}
else {
el1.innerHTML = '<p>not covered</p>';
}
Updated fiddle

Related

How to Scroll input into view but with some margin on top

Check the demo here: https://jsfiddle.net/g2djbwm5/1/
Scroll the page untill the input is visible.
Type in something but keep the focus into it
Using the mouse scroll the page again until the input is no longer visible
Now type in something
Input will be scrolled into view to the very top like this
Is there any way to show this input not very top but some 20px from the top when user type in? something like
Code:
<div style="width: 100%; height: 800px;">..............</div>
<input type="text"/>
<div style="width: 100%; height: 800px;" />
In CSS you can use this to make the scroll stops some px above:
scroll-margin-top: 50px;
an example here
Create a function to locate the y position of the element -> input. Then an event listener for input and conditional to check the position of the element. If it is off the page when focused and the event is input, place it on top and change the position to sticky else position relative.
let input = document.getElementById('input');
let inputPos = -1;
if (input === document.activeElement) {
input.addEventListener("input", () => {
if (inputPos < 0) inputPos = findPosY(input);
if (pageYOffset > inputPos) {
input.style.cssText = 'position:sticky; top: 0px; bottom: 0px;';
} else {
input.style.position = 'relative;';
}
});
}
function findPosY(obj) {
let curtop = 0;
if (typeof(obj.offsetParent) != 'undefined' && obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
curtop += obj.offsetTop;
} else if (obj.y)
curtop += obj.y;
return curtop;
}
<div style="width: 100%; height: 800px;">..............</div>
<input id="input" type="text" />
<div class="input" style="width: 100%; height: 1800px;" />
This decision comes to my mind, but this solution is a "crutch" (hack).
The problem with this solution is that when scrolling, the input loses its sticky positioning and returns its default coordinates.
If my small solution is modified, taking into account the preservation of the position of the input when scrolling, then the solution will be good, as it seems to me.
let input_text = document.querySelector('input[type="text"]');
input_text.oninput = function() {
this.classList.add('top_for_input');
}
window.onscroll = function() {
input_text.classList.remove('top_for_input');
}
.top_for_input {
position: sticky;
top: 20px;
bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width: 100%; height: 800px;">..............</div>
<input type="text"/>
<div style="width: 100%; height: 800px;" />

Dynamic ScrollTo function requires next element

Please have a look at my example.
I have multiple rows on my website and a scrollto() button, wich is always at the bottom of the screen.
Depending on where the usere is located on my site at a certain moment, I would like him to move to the next row after he clicked the button.
I am aware of how to make a user scrollto(), but I have no clue what kind of selector I should use.
function myFunction() {
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpace < min && divTopSpace > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
console.log(rows[next_idx]);
}
.rowOne {
height: 100vh;
background-color: peachpuff;
}
.rowTwo {
height: 100vh;
background-color: firebrick;
}
.rowThree {
height: 100vh;
background-color: deepskyblue;
}
.btn {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
}
<div class="main">
<div class="row rowOne">
<div class="a">
<div class="b">
Foo
</div>
</div>
</div>
<div class="row rowTwo">
<div class="a">
<div class="b">
Bar
</div>
</div>
</div>
<div class="row rowThree">
<div class="a">
<div class="b">
Foobar
</div>
</div>
</div>
<button id="btn" class="btn" onclick="myFunction()">Button</button>
</div>
Thank you in advance.
Since they are all the same height (100% of the window height), the simple solution would be to simply scroll by that amount.
window.scrollBy(0, window.innerHeight);
Otherwise, you'll need to detect which element is the "current" one, and then get it's next sibling, and then scroll to it. Something like this (haven't tested, so syntax might be off, but this should give you an idea)
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpave < min && divTopSpave > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
window.scrollTo(rows[next_idx].scrollTop);

Use editable div height change to add and remove classes to other DOM elements

I have and editable div that allow users to enter text. This is part of a chat widget so the design needs the box to be fixed to the bottom.
When a user types I need javascript to catch the resize and append classes to elements where needed.
I managed to get the box to resize upwards but I have had a lot of trouble scaling it back down again.
I have been stuck on this for days now, so any help now would be greatly appreciated.
I have the function and a basic UI version here JSFiddle
Its probably really simple but I am having no luck figuring this out
JSFiddle
var chatBoxSize = {
oldHeight : 0,
scrollHeight : 0,
lastClass : 1,
minClass : 1,
maxClass : 5,
min_height : 0,
last_size : 0,
getClass : function (size){
var sizes = [chatBoxSize.min_height, chatBoxSize.min_height * 2, chatBoxSize.min_height * 3, chatBoxSize.min_height * 4, chatBoxSize.min_height * 5];
switch (size){ case sizes[0] : return 1; break; case sizes[1] : return 2; break; case sizes[2] : return 3; break; case sizes[3] : return 4; break; case sizes[4] : return 5; break; };
//is not exact
var r = null;
console.log(size);
for(var x = 0; x < sizes.length; x++){
if(x < sizes.length){
if(size >= sizes[x] && size < sizes[(x + 1)]){
return (x + 1);
}
}
}
return chatBoxSize.maxClass;
}
};
$(function () {
chatBoxSize.min_height = parseInt($('#msgWriteArea').height());
chatBoxSize.max_height = chatBoxSize.min_height * 4;
chatBoxSize.last_size = chatBoxSize.min_height;
});
function updateChatSize() {
var id = '#msgWriteArea';
var element = document.querySelector(id);
var size = $(id)[0].scrollHeight;
var container = $('.container');
var toRemove = 'size_' + chatBoxSize.lastClass;
console.log(chatBoxSize.getClass(size));
chatBoxSize.lastClass = chatBoxSize.getClass(size);
console.log('Add new class', chatBoxSize.lastClass);
chatBoxSize.last_size = size;
$(id).removeClass(toRemove);
$(id).addClass('size_' + chatBoxSize.lastClass);
container.removeClass(toRemove);
container.addClass('size_' + chatBoxSize.lastClass);
$('#display').val('Removed ' + toRemove + ' Added ' + chatBoxSize.lastClass);
};
$(function (){
$('#msgWriteArea').bind('change keydown input', function () {
if(event.type == 'keydown'){
updateChatSize();
}
});
})
I have thought of just setting the heights to auto but that will not work with the rest of the ui elements.
Sorry to say but No JS needed at all
flex to the rescue, overflow-y: auto; and max-height to the editable DIV:
Heres a jsBin demo so you can play and resize the browser
*{box-sizing:border-box; -webkit-box-sizing:border-box;}
html, body{height:100%; margin:0;font:16px/1 sans-serif; color:#444;}
#chat{
display: flex;
flex-direction: column;
height:100%;
}
#messages{
flex:1;
overflow-y: auto;
}
#messages > div{
padding: 24px;
background: #eef;
margin: 4px 0;
}
#ui{
background: #eee;
}
#msgWriteArea{
padding: 24px;
overflow-y: auto;
height:100%;
background:#ddd;
max-height:100px; /* if max height is exceeded */
overflow-y: auto; /* add scrollbars */
}
<div id="chat">
<div id="messages">
<div>Message 1</div>
<div>Message 2</div>
<div>Message 3</div>
<div>Message 4</div>
<div>Message 5</div>
<div>Message 6</div>
</div>
<div id="ui">
<div id="msgWriteArea" contenteditable>Some text message</div>
</div>
</div>
Now, if you still really need to the the message area height (for some reasons) you could count the number of lines using JS.

Why running my js resizer code makes document to be more than 100% of window height and width in IE7 - IE11 and MS Edge?

The script purpose is to change some special divs size without using width and height CSS properties.
<html>
<head>
<title>Test resizer</title>
<script type = 'text/javascript'>
function endsWith(str, suffix)
{
if (!str)
return false;
return str.toString().indexOf(suffix, str.length - suffix.length) >= 0;
}
function fixSizeFor(start_elem)
{
if (document && document.body)
{
var curr_elem = start_elem ? start_elem : document.body;
var force_size = curr_elem.getAttribute("data-forcesize");
if (force_size && curr_elem.parentNode.style.position.toLowerCase() == "relative" && curr_elem.style.position.toLowerCase() == "absolute")
{
var needed_width_str = curr_elem.getAttribute("data-neededwidth");
var needed_height_str = curr_elem.getAttribute("data-neededheight");
if (endsWith(needed_width_str, "%"))
{
var n_w = needed_width_str.substr(0, needed_width_str.length - 1)
var calculated_w = (curr_elem.parentNode.clientWidth * n_w) / 100;
if (curr_elem.style.width != calculated_w + "px")
curr_elem.style.width = calculated_w + "px";
}
if (endsWith(needed_height_str, "%"))
{
var n_h = needed_height_str.substr(0, needed_height_str.length - 1)
var calculated_h = (curr_elem.parentNode.clientHeight * n_h) / 100;
if (curr_elem.style.height != calculated_h + "px")
curr_elem.style.height = calculated_h + "px";
}
}
for (var i = 0; i < curr_elem.children.length; i++)
fixSizeFor(curr_elem.children[i]);
}
}
setInterval(function () { fixSizeFor(null); }, 100); //comment this and weird space gone
</script>
</head>
<body>
<table border = '1' style = "width: 100%; height: 100%;">
<tr>
<td style = 'position: relative;'>
<div data-forcesize = 'true' data-neededwidth = '100%' data-neededheight = '100%' style = 'position: absolute; top: 0px; left: 0px; overflow: auto; border: dashed;'>Why the hell there is some space under table border?!</div>
</td>
</tr>
</table>
</body>
</html>
Weird space appears in IE7 - IE11 and MS Edge. Opera 15 and latest Chrome are fine.
How I can avoid this?
Okay, Changing your html to this will resolve your "Weird space". You could fine tune this by changing your calculation of the width and height, or just changing your data-neededwidth and data-neededheight attributes like I did.
<html>
<head>
<title>Test resizer</title>
<script type = 'text/javascript'>
function endsWith(str, suffix)
{
if (!str)
return false;
return str.toString().indexOf(suffix, str.length - suffix.length) >= 0;
}
function fixSizeFor(start_elem)
{
if (document && document.body)
{
var curr_elem = start_elem ? start_elem : document.body;
var force_size = curr_elem.getAttribute("data-forcesize");
if (force_size && curr_elem.parentNode.style.position.toLowerCase() == "relative")
{
var needed_width_str = curr_elem.getAttribute("data-neededwidth");
var needed_height_str = curr_elem.getAttribute("data-neededheight");
if (endsWith(needed_width_str, "%"))
{
var n_w = needed_width_str.substr(0, needed_width_str.length - 1);
var calculated_w = (window.innerWidth * n_w) / 101;
if (curr_elem.style.width != calculated_w + "px")
curr_elem.style.width = calculated_w + "px";
}
if (endsWith(needed_height_str, "%"))
{
var n_h = needed_height_str.substr(0, needed_height_str.length - 1);
var calculated_h = (window.innerHeight * n_h) / 101;
if (curr_elem.style.height != calculated_h + "px")
curr_elem.style.height = calculated_h + "px";
}
}
for (var i = 0; i < curr_elem.children.length; i++)
fixSizeFor(curr_elem.children[i]);
}
}
setInterval(function () { fixSizeFor(null); }, 100); //comment this and weird space gone
</script>
</head>
<body>
<table id="table" border = '1' style = "width: 100%; height: 100%;">
<tr>
<td style = 'position: relative;'>
<div data-forcesize = 'true' data-neededwidth = '99%' data-neededheight = '97.5%' style = 'position: relative; top: 0; left: 0; overflow: auto; border: dashed;'>Why the hell there is some space under table border?!</div>
</td>
</tr>
</table>
</body>
</html>
Sometimes with IE you have to be specific with your heights since it is really strict when it comes to calculated height.
What about this:
http://codepen.io/jonathan/pen/qOzbMa/
I added in the CSS for html and the body tags height: 100%. Which allows its descendants (children) in the DOM to extend their height to the bottom of their parent.
html, body {
height:100%; /* important to allow children to inherit */
}
I removed position relative off of the td since tables and position relative are buggy in IE. Its better to just nest another div tag as the parent for your absolutely position div.
<table border="1" style="width: 100%; height: 100%;">
<tr>
<td>
<!--
height 100% on both relative and absolute positioned
elements to extend their height to bottom of their parent.
that is why the html and body tag have their height 100%
which allows its children to inherit the height 100%
-->
<div style='position: relative; height: 100%;'>
<div style='width: 100%; height: 100%; position: absolute; top: 0px; left: 0px; overflow: auto; border: dashed;' data-forcesize='true' data-neededwidth='100%' data-neededheight='100%'>Why the hell there is some space under table border?!</div>
</div>
</td>
</tr>
</table>
I also added height:100% to the div with position: relative, so it extends its height to the bottom of its parent. I also added width:100% and height:100% to your div with position: absolute, so the div extends its height to the bottom of its parent.
Tables in IE are buggy with height, especially if you use position relative on a td (table-data cell), since it's display property is set to table-cell. Unlike a div tag's default display property which is block.

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

Categories

Resources