Background image swap animation - javascript

I have a grid and each div has a background image. I am trying to create a fade out/in image swapping effect. Currently I'm getting two random divs and inserting one background-image URL into the other. Problem is, after a while all the images wind up the same. I think I need to reset the background URL to the original value (image) each time, but I'm not sure how to do that.
So the order would be:
original image fades out,
new image fades in,
new image fades out,
original image fades in
Any help greatly appreciated!
Currently I have this fiddle:
JS:
var $squares = $('.box');
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
var square2 = $squares.eq([Math.floor(Math.random()*$squares.length)])
var square1Url = square1.css('background-image').replace(/(url\(|\)|")/g, '');
var square2Url = square2.css('background-image').replace(/(url\(|\)|")/g, '');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square2Url + ")");
$(this).fadeIn(1500);
});
timeoutId = setTimeout(imgFade, 1500);
}
imgFade();
HTML:
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')"></div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')"></div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')"></div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')"></div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')"></div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')"></div>
</div>
CSS:
body {margin:0}
.grid-container {width:100%;}
.box {
width:20vw;
height:33.33vh;
float:left;
border:1px solid white;
background-size: cover;
background-position:center;
}

Since you are changing the background-image url in a random element, each time you are going to potentially lose a url if the other url is a copy of one of the others.
You could parse all the urls and keep them in an array and grab the urls randomly from that array instead of the elements themselves since you will be changing the elements.
var $squares = $('.box');
//create an array from all the backgroundImage values
var urls = $squares.map(function(){
return this.style.backgroundImage;
});
Then in imgFade
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
//get random urls from the array instead of the elements
var square1Url = urls[Math.floor(Math.random()*$squares.length)];
var square2Url = urls[Math.floor(Math.random()*$squares.length)];
Demo
var $squares = $('.box');
var urls = $squares.map(function() {
return this.style.backgroundImage;
});
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random() * $squares.length)])
var square1Url = urls[Math.floor(Math.random() * $squares.length)];
var square2Url = urls[Math.floor(Math.random() * $squares.length)];
$(square1).fadeOut(1500, function() {
$(this).css("background-image", square2Url);
$(this).fadeIn(1500);
});
timeoutId = setTimeout(imgFade, 1500);
}
imgFade();
body {
margin: 0
}
.grid-container {
width: 100%;
}
.box {
width: 20vw;
height: 33.33vh;
float: left;
border: 1px solid white;
background-size: cover;
background-position: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')">
</div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')">
</div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')">
</div>
</div>
Side note you dont need to do the url() replace since you are just adding it back in when setting the new background.
Also you will end up with multiple duplicates since it is random. But you won't end up just having a single url being used. If you don't want multiple duplicates, eg more than 2 duplicates at a time, you would need to write a check to see if that url has been used more than once and if so get a different one until you get one that hasn't been.
If you want no duplicates at all you would have to swap 2 backgrounds at once instead of just one at a time. This would be a bit easier code wise but does require changing two at a time.
In this one you would do as you were but add in the change to the second element as well
var square1 = $squares.eq([Math.floor(Math.random()*$squares.length)])
//modified to not select square1
var square2 = var square2 = $squares.not(square1).eq([Math.floor(Math.random() * $squares.length-1)])
var square1Url = square1.css('background-image').replace(/(url\(|\)|")/g, '');
var square2Url = square2.css('background-image').replace(/(url\(|\)|")/g, '');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square2Url + ")");
$(this).fadeIn(1500);
});
$(square2).fadeOut(1500, function() {
$(this).css("background-image", "url(" + square1Url + ")");
$(this).fadeIn(1500);
});
You would also need to increase the timeout to 3000 so that you don't accidently trigger a new transition while one is already taking place.
var $squares = $('.box');
var urls = $squares.map(function() {
return this.style.backgroundImage;
});
function imgFade() {
var square1 = $squares.eq([Math.floor(Math.random() * $squares.length)])
//modified to make sure we dont accidently
//select square1
var square2 = $squares.not(square1).eq([Math.floor(Math.random() * $squares.length-1)])
var square1Url = square1.css('background-image');
var square2Url = square2.css('background-image');
$(square1).fadeOut(1500, function() {
$(this).css("background-image", square2Url);
$(this).fadeIn(1500);
});
$(square2).fadeOut(1500, function() {
$(this).css("background-image", square1Url)
$(this).fadeIn(1500);
});
//change timing so it doesnt get called
//in the middle of a transition
timeoutId = setTimeout(imgFade, 3000);
}
imgFade();
body {
margin: 0
}
.grid-container {
width: 100%;
}
.box {
width: 20vw;
height: 33.33vh;
float: left;
border: 1px solid white;
background-size: cover;
background-position: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-container">
<div class="box" style="background-image: url('https://www.catster.com/wp-content/uploads/2017/11/A-Siamese-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.hswstatic.com/w_907/gif/tesla-cat.jpg')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg')">
</div>
<div class="box" style="background-image: url('https://www.shelterluv.com/sites/default/files/animal_pics/464/2016/11/25/22/20161125220040.png')">
</div>
<div class="box" style="background-image: url('https://r.ddmcdn.com/w_830/s_f/o_1/cx_0/cy_66/cw_288/ch_162/APL/uploads/2014/10/cat_5-1.jpg')">
</div>
<div class="box" style="background-image: url('https://cdn.theatlantic.com/assets/media/img/mt/2017/06/shutterstock_319985324/lead_720_405.jpg?mod=1533691890')">
</div>
</div>

Related

How to remove random div js

http://prntscr.com/p9u6f9
I create random divs using:
let div1 = 'div_list';
let div2 = div1 + [Math.floor(Math.random()*24)];
node.setAttribute('id', div2);
And I want remove div using button, but how can I remove this, not having ID? Because the ID is random.
function remove() {
console.log(div);
let remove = document.getElementById(??????????);
remove.remove();
}
Add an eventListener upon the creation of the node and call remove with the generated id :
let div1 = "div_list";
let div2 = div1 + [Math.floor(Math.random() * 24)];
node.setAttribute("id", div2);
node.addEventListener("click", () => remove(div2)); // add the event listener for the button of deletion if you're creating it with the div
function remove(id) {
console.log(id);
let remove = document.getElementById(id);
remove.remove();
}
Just try this example, it's 100% working.
function randRemove() {
var divCount = 5;
var randNumber = Math.floor(Math.random() * divCount) + 1;
var randSelect = document.getElementById("div-" + randNumber);
randSelect.remove();
alert("Div Removed: " + "div-" + randNumber);
}
.just-style {
display: inline-block;
width: 300px;
height: 100px;
margin: 20px;
}
<button id="randRemove" onclick="randRemove()">Remove Random Div</button>
<div id="main-div">
<div id="div-1" class="just-style" style="background-color: red;"></div>
<div id="div-2" class="just-style" style="background-color: blue;"></div>
<div id="div-3" class="just-style" style="background-color: aqua;"></div>
<div id="div-4" class="just-style" style="background-color: violet;"></div>
<div id="div-5" class="just-style" style="background-color: forestgreen;"></div>
<!--AND MORE DIV ... -->
</div>
Enjoy and good luck =D

jQuery - element crossing another element

I have a fixed div on the page which contains a logo and as the user scrolls and this logo passes over other divs I wnat to the change the colour of the logo.
I have this working over a single div but need to it work across multiple so any help appreciated.
The WIP site can be seen here... dd.mintfresh.co.uk - if you scroll down you'll (hopefully) see the logo change from black to white as it crosses an illustrated egg. I need the same to happen when it crosses other divs further down the page.
The script so far...
jQuery(window).scroll(function(){
var fixed = jQuery("logo");
var fixed_position = jQuery("#logo").offset().top;
var fixed_height = jQuery("#logo").height();
var toCross_position = jQuery("#egg").offset().top;
var toCross_height = jQuery("#egg").height();
if (fixed_position + fixed_height < toCross_position) {
jQuery("#logo img").css({filter : "invert(100%)"});
} else if (fixed_position > toCross_position + toCross_height) {
jQuery("#logo img").css({filter : "invert(100%)"});
} else {
jQuery("#logo img").css({filter : "invert(0%)"});
}
}
);
Any help appreciated. Thanks!
you need to fire a div scroll event. you can assign
$("div1").scroll(function(){
//change the color of the div1
}
});
$("div2").scroll(function(){
//change the color of the div2
}
});
or you can assign a class to divs which you want to change the color
$(".div").scroll(function(){
//change the color of the div which you are scrolling now
}
});
You can use like this :-
$(window).scroll(function() {
var that = $(this);
$('.section').each(function() {
var s = $(this);
if (that.scrollTop() >= s.position().top) {
if(s.hasClass('active')) {
$('.logo').addClass('invert');
} else {
$('.logo').removeClass('invert');
}
}
});
});
body {
padding: 0;
margin: 0;
}
div {
background: #f00;
height: 400px;
}
.logo {
position: fixed;
top: 0;
left: 0;
width: 100px;
}
.logo.invert {
filter: invert(100%);
}
div:nth-child(even) {
background: #ff0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://dd.mintfresh.co.uk/wp-content/uploads/2018/06/DD_logo.svg" class="logo" />
<div id="page1" class="section"></div>
<div id="page2" class="section active"></div>
<div id="page3" class="section"></div>
<div id="page4" class="section active"></div>
<div id="page5" class="section"></div>
As your site code you can do like this :
$(window).scroll(function() {
var that = $(this);
$('#content > section').each(function() {
var s = $(this);
if (that.scrollTop() >= s.position().top) {
if(s.hasClass('black')) {
$('#logo img').css({filter: 'invert(0%)'});
} else {
$('#logo img').css({filter: 'invert(100%)'});
}
}
});
});

How to use jQuery to select an image being hovered over?

Outline
My intention is for the user to hover over an image, and an overlaying div with reduced opacity will appear over the top of it. The overlaying laying div has a height of 0px and when hovered it should increase the height value to exactly half of the image height.
The hover function is working but I think this line is wrong:
EDIT
After trying to log the curHeight variable (which was 'undefined') i think this line must be creating the issue:
var curHeight = landingImg.clientHeight;
HTML:
<div id="landing-images">
<div class="leftLanding">
<div class="imageCover">
</div>
<img class="landingImage" src="assets/landingIMG1.png">
</div>
<div class="rightLanding">
<div class="imageCover">
</div>
<img class="landingImage" src="assets/landingIMG1.png">
</div>
</div>
JS:
$(".landingImage").hover(function () {
console.log("hover works");
var landingImg = $(this);
var curHeight = landingImg.clientHeight;
$(this).closest('.imageCover').css("height", curHeight / 2);
}, function () {
$(this).closest('.imageCover').css("height", "0px");
});
You should use .siblings() instead and you must add width to div or it won't show, and use .height() and .width() to get the height and the width of the image
$(".landingImage").hover(function () {
var landingImg = $(this);
var curHeight = landingImg.height();
var curWidth = landingImg.width();
$(this).siblings('.imageCover').css("height", curHeight / 2);
$(this).siblings('.imageCover').css("width", curWidth);
}, function () {
$(this).siblings('.imageCover').css("height", "0px");
$(this).siblings('.imageCover').css("width", "0px");
});
.leftLanding,
.rightLanding {
position: relative;
}
.imageCover {
background: green;
position: absolute;
top: 0;
z-index: 111;
opacity:.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="landing-images">
<div class="leftLanding">
<div class="imageCover">
</div>
<img class="landingImage" src="https://www.w3schools.com/css/img_fjords.jpg">
</div>
<div class="rightLanding">
<div class="imageCover">
</div>
<img class="landingImage" src="https://www.w3schools.com/css/img_fjords.jpg">
</div>
</div>
.clientHeight is a DOM property.
Change
var curHeight = landingImg.clientHeight;
To
var curHeight = landingImg.height();
Or
var curHeight = this.clientHeight;

Could help me to resolve mouse events?

<script>
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","move","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[2].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
</script>
Hi!!! I need help!!!
I made a object of "div".
and then I added one more "div" into first "div".
second "div" is a red box. You can see it when you click the "+"mark.
But, second "div" has mouse event, and the event does not work.
I want to change mouse cursor when cursor become on the red box.
Why does not the mouse event work?
My last purpose is to make window object.
And there will be a lot of mouse events.
I already made window object similar to this one. However, it also did not work.
How can I try mouse event?
This is my full source: https://drive.google.com/file/d/0B4p8lZSEMXcqZUdacVJyVlBiUWc/view?usp=sharing
This is a CSS issue. Your problem is here:
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
Specifically, where you set the z-index to -1, by doing so you place the div and everything contained in it under the active layer so to speak. As such the hover event doesn't propagate to your div. change this to 1 and the cursor will behave as expected.
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","pointer","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[1].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
#buttonToOpenWindow{
width:50px;
height:20px;
border: 1px solid #DCDCDC;
margin: 2px;
position:fixed;
left:-1px;
top:0px;
}
#buttonToOpenWindow div.positionOfPlus{
width:20px;
height:20px;
position:absolute;
left:30px;
}
div.wrapOfPlus{
width:20px;
height:20px;
}
div.inside01{
width:15px;
height:5px;
background-color: #B0C4DE;
position:absolute;
left:2.5px;
top:7.5px;
}
div.inside02{
width:5px;
height:15px;
background-color: #B0C4DE;
position:absolute;
left:7.5px;
top:2.5px;
}
<section id="section0">
<div id="buttonToOpenWindow" onclick="openWindow()">
<div class="positionOfPlus">
<div class="wrapOfPlus">
<div class="inside01"></div>
<div class="inside02"></div>
</div>
</div>
</div>
</section>
<footer>
<br><br><br><br><br>
<div style="display:inline-flex;">00: <div id="0"></div></div><br>
<div style="display:inline-flex;">01: <div id="1"></div></div><br>
<div style="display:inline-flex;">02: <div id="2"></div></div><br>
<div style="display:inline-flex;">03: <div id="3"></div></div><br>
<div style="display:inline-flex;">04: <div id="4"></div></div><br>
<div style="display:inline-flex;">05: <div id="5"></div></div><br>
<div style="display:inline-flex;">06: <div id="6"></div></div><br>
<div style="display:inline-flex;">07: <div id="7"></div></div><br>
<div style="display:inline-flex;">08: <div id="8"></div></div><br>
<div style="display:inline-flex;">09: <div id="9"></div></div><br>
<div style="display:inline-flex;">10: <div id="10"></div></div><br>
<div style="display:inline-flex;">11: <div id="11"></div></div><br>
<div style="display:inline-flex;">12: <div id="12"></div></div><br>
<div style="display:inline-flex;">13: <div id="13"></div></div><br>
<div style="display:inline-flex;">14: <div id="14"></div></div><br>
<div style="display:inline-flex;">15: <div id="15"></div></div><br>
<div style="display:inline-flex;">16: <div id="16"></div></div><br>
<div style="display:inline-flex;">17: <div id="17"></div></div><br>
<div style="display:inline-flex;">18: <div id="18"></div></div><br>
<div style="display:inline-flex;">19: <div id="19"></div></div><br>
<div style="display:inline-flex;">20: <div id="20"></div></div><br>
<div style="display:inline-flex;">21: <div id="21"></div></div><br>
<div style="display:inline-flex;">22: <div id="22"></div></div><br>
<div style="display:inline-flex;">23: <div id="23"></div></div><br>
<div style="display:inline-flex;">24: <div id="24"></div></div><br>
<div style="display:inline-flex;">25: <div id="25"></div></div><br>
<div style="display:inline-flex;">26: <div id="26"></div></div><br>
<div style="display:inline-flex;">27: <div id="27"></div></div><br>
<div style="display:inline-flex;">28: <div id="28"></div></div><br>
<div style="display:inline-flex;">29: <div id="29"></div></div><br>
<div style="display:inline-flex;">30: <div id="30"></div></div><br>
<div style="display:inline-flex;">111: <div id="111"></div></div><br>
<div style="display:inline-flex;">222: <div id="222"></div></div><br>
<div style="display:inline-flex;">333: <div id="333"></div></div><br>
<div style="display:inline-flex;">444: <div id="444"></div></div><br>
<div style="display:inline-flex;">555: <div id="555"></div></div><br>
<div style="display:inline-flex;">666: <div id="666"></div></div><br>
<div style="display:inline-flex;">777: <div id="777"></div></div><br>
<div style="display:inline-flex;">888: <div id="888"></div></div><br>
<div style="display:inline-flex;">999: <div id="999"></div></div><br>
</footer>

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