
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 aclick
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
HTML
<div id="pagiImg"> <a id="rotatingHref" href="[DEFAULT LINK HERE]" target="_blank"> <img id="rotatingImg" src="[DEFAULT IMAGE LINK HERE]" /> </a> </div>
CSS
#pagiImg{border:1px solid steelblue;width:198px;height:400px;} #pagiImg img{width:198px;height:400px;}
JQuery
$(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]); });
Demo
Note
One thing to point out is that the current code, always assume that thearrayOfImg
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.
No comments :
Post a Comment