Mvrk
Mvrk

Reputation: 225

Simple image slider is not working

I want to make simple image slider. Everything works fine till you reach the last image (div). When the slider starts again, the first image covers all other images. I have tried to change z-index of images (divs) but still I have the same problem .

var index = 1;
function whichimg()
{
    $('#trace').text('image index ' + index);
    if (index < 5)
    {
        changeimg(index);
        index = index + 1;
    }
    else
    {
        index = 1;
    }
}

function changeimg(indexofImg)
{
    $('#imgid' + indexofImg).slideToggle();
}

setInterval(whichimg, 1000);
#imggruop li {
    display: inline;
    float: left;
    list-style: none;
}

#imagewapper {
    width: 600px;
    height: 400px;
    overflow: hidden;
}

#imgid1, #imgid2, #imgid3, #imgid4 {
    width: 300px;
    height: 300px
}

#imgid1 { background-color: #ff0000; }
#imgid2 { background-color: #63ff1b; }
#imgid3 { background-color: #fff717; }
#imgid4 { background-color: #2a6aff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="trace"></div>

<div id="imagewapper" >
    <ul id="imggruop">
        <li><div id="imgid1"> IMAGE 1 </div></li>
        <li><div id="imgid2"> IMAGE 2 </div></li>
        <li><div id="imgid3"> IMAGE 3 </div></li>
        <li><div id="imgid4"> IMAGE 4 </div></li>
      </ul>
</div>

Upvotes: 2

Views: 168

Answers (3)

Mvrk
Mvrk

Reputation: 225

The solution is pretty simple i just add this line to my code and evety thing work fine !

since the slideToggle set the display to none , at the end of the slide show i have to re-show all the images before slider start again :D

 $('#imgid1,#imgid2,#imgid3,#imgid4').show();

Upvotes: 0

Tushar Gaurav
Tushar Gaurav

Reputation: 506

@Florin Pop's answer works fine. I am just adding one more easy method to achieve the same. Just replace your javascript code with

function changeimg()
{  
    marginTop = $("#imagewapper").outerHeight();
    $("#imggruop").animate({
        marginTop: -(marginTop)+"px"
      },1000,function(){

      firstEl = $("#imggruop").children("li:first");
      $("#imggruop").children("li:first").remove();
      $("#imggruop").css("margin-top","0");
      $("#imggruop").append(firstEl);
   });     
}

setInterval(changeimg, 1500);

See the fiddle here

Upvotes: 0

Florin Pop
Florin Pop

Reputation: 5135

You can add the following code in the changeimg function:

$('#imgid' + indexofImg).slideUp();
if (index == 4) {
    for (var x = 1; x < 5; x++) {
        $('#imgid' + x).slideDown();   
    }
}

Example here.

Upvotes: 2

Related Questions