4

I just made a very simple "imageslider" but it does not slide, so lets call it a "imageswapper".

Alright. My question is now, how can I make it slide in and slide out so its smooth.

JSFIDDLE

[JS]

document.getElementById('atwo').style.display = "none";
    function ImgSwap(){
        if(document.getElementById('one').style.display == "block"){
        document.getElementById('one').style.display = "none";
        document.getElementById('two').style.display = "block";
        }else{
        document.getElementById('two').style.display = "none";
        document.getElementById('one').style.display = "block";
        }
    }

[HTML]

<div id="wrapper">
<a onclick="ImgSwap()" id="aone"><img src="one.jpg" alt="one" class="img" id="one" /></a>
<a onclick="ImgSwap()" id="atwo"><img src="two.gif" alt="two" class="img" id="two" /></a>
</div>

[CSS]

        img.img
    {
        height: 200px;
        width: 300px;
    }
    #one
    {
        display: block;
    }
    #two
    {
        display:none;
    }
    a:hover
    {
        cursor: pointer;
    }
    div#wrapper
    {
        width: 300px;
    }
SwegreDesigns
  • 189
  • 2
  • 17

1 Answers1

3

There are many ways to achieve this effect, one way to do this is by applying css transition to your css class. You can change the opacity and position of the image to create the slides in effect.

function ImgSwap() {
  document.getElementById('one').classList.toggle('show');
  document.getElementById('two').classList.toggle('show');
}
div#wrapper {
  width: 300px;
  height: 200px;
  position: relative;
  background-color: black;
}
.img {
  height: 200px;
  width: 300px;
  position: absolute;
  top: 0;
  left: -300px;
  opacity: 0;
}
a:hover {
  cursor: pointer;
}
.show {
  left: 0;
  opacity: 1;
  transition: left 1s;
}
<div id="wrapper">
  <a onclick="ImgSwap()" id="aone">
    <img src="https://c2.staticflickr.com/6/5120/5824578555_d239d42195_b.jpg" alt="one" class="img show" id="one" />
  </a>
  <a onclick="ImgSwap()" id="atwo">
    <img src="http://petsadviser.supercopyeditors.netdna-cdn.com/wp-content/uploads/2012/06/why-is-cat-scared-rain-thunder.png" alt="two" class="img" id="two" />
  </a>
</div>
Amy
  • 726
  • 8
  • 5
  • Thank you Amy, but how can I improve the code so there's no delay? I found that the transition selector is doing that, instead of all, can I target just the slide transition and not the delay transition? – SwegreDesigns Jun 07 '15 at 19:59
  • @SwegreDesigns, I made an edit to the code above. I changed the transition to only affect the left value and I have also updated the hidden left position to be the negative full width value of the image. – Amy Jun 07 '15 at 20:37