Tuesday, August 25, 2015

Image change on onClick event and slideshow image - basic image slide with minimum effort

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image change using on click method</title>
    <style>
        #img_div {
            height: 400px;
            overflow: hidden;
        }
        .profile img{
            height: 100%;
            width: auto;
        }
    </style>
</head>
<body>
<div class="profile">
    <div id="img_div"> </div> <br>
    <button id="prev" class="btn btn-success" onclick="prev_img()">Prev</button>
    <button id="next" class="btn btn-success" onclick="next_img()">Next</button>
    <br> <br>
</div>

<script>
//    img path variable will define path of individual image;
    var img_path = ["images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg", "images/5.jpg", "images/6.jpg"]
    var img_div =  document.getElementById('img_div');
    var img_tag = document.createElement("img");
    img_tag.className = "img-responsive";
    img_div.appendChild(img_tag);
    var index = 0;
    img_tag.src = img_path[index];
    var prev = document.getElementById('prev');
    var next = document.getElementById('next');
    if(index == 0){
        prev.disabled = true;
    }
    function next_img(){
        index++;
        if(index < img_path.length){
            img_tag.src = img_path[index];
            prev.disabled = false;
        } else{
            index = 0;
            img_tag.src = img_path[index];
            prev.disabled = true;
        }
    }
        setInterval(next_img, 2000);

    function prev_img(){
        index--;
        img_tag.src = img_path[index];
        if(index == 0){
            prev.disabled = true;
        }
    }
</script>
</body>
</html>

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }