Create a Banner with Link that Changes Everytime You Load a Page
It seems that I got the idea wrong from my previous post. Initially, what she wanted was to add a banner or an image that changes every time she visits another page (or even when refreshing the current page).

Technically, we wanted to replicate the code created by advertising sites such as AdSense. With this, the image and links changes every time the web page loads making a dynamic appeal rather than a boring static image.

Changing the 'old code'

Based on the previous code, we are updating the image and link by adding a click handler on the pagination. Since we are not needing the pagination anymore, we will remove that part of the code making the click function useless.

Still, we need to make the image and link change but this time we will make it random. In this matter, we will be using the code for creating random numbers and limiting it depending on the number of links that we are going to display.

This is the code for creating random number, where N is the limiter:

var numberRand = Math.floor(Math.random() * N);

Applying this to our code, we'll get:

var numberRand = Math.floor(Math.random() * arrayOfImg.length);

And so, this will generate a random number that we can use as index to refer on one of our items inside the array of images and links.

The Code


<div id="pagiImg">
    <a id="rotatingHref" href="[DEFAULT LINK HERE]" target="_blank">
        <img id="rotatingImg" src="[DEFAULT IMAGE LINK HERE]" />


#pagiImg{border:1px solid steelblue;width:198px;height:400px;}
#pagiImg img{width:198px;height:400px;}


$(document).ready(function() {
 // place image links here
    arrayOfImg = ["img1.png", "img2.png", "img3.png"];
    // place all links here
    arrayOfHref = ["link1.html", "link2.html", "link3.html"];,

    var numberRand = Math.floor(Math.random() * arrayOfImg.length);

    $("#rotatingHref").attr("href", arrayOfHref[numberRand]);
    $("#rotatingImg").attr("src", arrayOfImg[numberRand]);



One thing to point out is that the current code, always assume that the arrayOfImg is always equal to arrayOfHref in terms of length.

Though, later on you can actually just add something that can do the checking or an error handling in such cases that both arrays are not equal.

Final Words

As I always say, this may not be the best solution for this matter, and there could be a thousand widgets out there that might do it. This is just a quick draft that I made and my only aim for creating this is to show the basic algorithm in creating this feature using scripts. :)

No comments :

Post a Comment