Create a Rotating Image with Links Using JQuery
I found a question on Facebook asking for a code regarding a rotating banner/image similar to what AdSense has (please refer to the picture). But, in this case, she wanted an image to be shown and a link attached to it every time she changes the page.

Though, I'm not exactly sure that I got what she wanted, I tried to come up with my own code that shows a slide show like pagination that uses JQuery.

Scenario

Create a rotating image similar to AdSense. This should provide an paginated slide show that has an image and is clickable.

Code

HTML

<div id="pagiImg">
    <a id="rotatingHref" href="http://inkperweek.tumblr.com/post/34071658607/traxex-the-drow-ranger-by-aj-banda" target="_blank">
        <img id="rotatingImg" src="http://24.media.tumblr.com/tumblr_mc9tpsX8Up1rfygheo1_250.jpg" />
    </a>
</div>

<div id="pagi">
    <a href="#" id="prevBtn"> &lt; </a>
        &middot; 
    <a href="#" id="nextBtn"> &gt; </a>
</div>

JQuery

$(document).ready(function() {
    // add all image links here
    arrayOfImg = ["image1.png", "image2.png", "image3.png"];
    
 // add all links here
    arrayOfHref = ["link1.html", "link2.html", "link3.html"];

    ctr = 0;
    $("#prevBtn").click(function() {
        prevPage();
    });
    $("#nextBtn").click(function() {
        nextPage();
    });

    function nextPage() {
        ctr++;
        if (ctr > arrayOfImg.length - 1) ctr = 0;
        console.log(ctr);
        $("#rotatingHref").attr("href", arrayOfHref[ctr]);
        $("#rotatingImg").fadeOut(400, function() {
            $("#rotatingImg").attr("src", arrayOfImg[ctr])
        }).fadeIn(400);

        console.log($("#rotatingHref").attr("src"));
    }

    function prevPage() {
        ctr--;
        if (ctr < 0) ctr = arrayOfImg.length - 1;
        console.log(ctr);
        $("#rotatingHref").attr("href", arrayOfHref[ctr]);
        $("#rotatingImg").fadeOut(400, function() {
            $("#rotatingImg").attr("src", arrayOfImg[ctr])
        }).fadeIn(400);

        console.log($("#rotatingHref").attr("src"));
    }
});

CSS

#pagi{
    text-decoration:none;
    font-weight:bold;
    background-color:steelblue;
    width:400px;
    color:#ffffff;
    text-align:center;
}
#pagi a{color:#ffffff;text-decoration:none;font-weight:bold;}
#pagiImg{border:1px solid steelblue;width:398px;height:600px;}
#pagiImg img{width:398px;height:600px;}

Demo

No comments :

Post a Comment