Manigandan Manigandan - 7 months ago 12
Javascript Question

How to add link on slider images

i have used the following code for image slider. and how can i set the link to each images

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var imageID=0;
function changeimage(every_seconds){
//change the image
if(!imageID){
document.getElementById("myimage").src="1.png";
imageID++;
}
else{if(imageID==1){
document.getElementById("myimage").src="2.png";
imageID++;
}else{if(imageID==2){
document.getElementById("myimage").src="3.png";
imageID=0;
}}}
//call same function again for x of seconds
setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
</script>
</head>

<body style='background:black;' onload='changeimage(2)'>
<div style='position:absolute;width:100%;height:100%;left:0px;top:0px;' align='center'><img width='700px' height='100px' id='myimage' src='http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg'/></div>
</body>
</html>


please tell how to add link to each images

Answer

You can do like your image src.

use .setAttribute('href', "yoururl"); for set a html attribute with JS.

Add a link around your images and change the href attribute.

<script type='text/javascript'>
var imageID=0;
function changeimage(every_seconds){
   var link = document.getElementById("mylink");
    //change the image
    if(!imageID){
        document.getElementById("myimage").src="1.png";
        link.setAttribute('href', "url1");
        imageID++;
    }
    else{if(imageID==1){
        document.getElementById("myimage").src="2.png";
        link.setAttribute('href', "url2");
        imageID++;
    }else{if(imageID==2){
        document.getElementById("myimage").src="3.png";
        link.setAttribute('href', "url3");
        imageID=0;
    }}}
    //call same function again for x of seconds
    setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
</script>
</head>

<body style='background:black;' onload='changeimage(2)'>
  <div style='position:absolute;width:100%;height:100%;left:0px;top:0px;' align='center'>
   <a id="mylink" href="#">
    <img width='700px' height='100px' id='myimage' src='http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg'/>
   </a>
  </div>
</body>    
</html> 
Comments