I have some restriction within the programme, it would be nice if the
solution doesn't need JQuery, as I have mention above, it does have some
restriction.
What i am trying to achieve is.
Change an image with JavaScript dynamically. (Done)
Each image will lead to a different link when user click on it. (Need help!)
Below is my current code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var image1=new Image()
image1.src="image_1.jpg"
var image2=new Image()
image2.src="image_2.jpg"
var image3=new Image()
image3.src="image_3.jpg"
var step = 1
function slideit(){
document.images.slide.src=eval("image"+step+".src")
if(step<3) step++
else step=1
setTimeout("slideit()",2500)
}
slideit()
function inputhref() {
var href = 'https://www.google.ca/';
window.open(href)
}
</script>
</head>
<body>
<img src="image_1.jpg" name="slide" width="400" height="400"
onclick="inputhref()">
There were few errors which I solved, and now it works!
window.location.href
for opening an url in the same window.
document.querySelector()
for selecting element(s).
Call setTimeout()
with function name without using ''
.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="image_1.jpg" id="slide" width="100" height="100"
onclick="inputhref()">
<script type="text/javascript">
var image1=new Image()
image1.src="https://image_1.jpg"
var image2=new Image()
image2.src="https://image_2.jpg"
var image3=new Image()
image3.src="https://image_3.jpg"
var step = 1
var slide = document.querySelector('#slide');
var timer
function slideit(){
slide.src="https://image_"+step+".jpg"
if(step<3) step++
else step=1
console.log('Image changed to ' + slide.src);
timer = setTimeout(slideit,2500)
}
slideit();
function inputhref() {
window.location.href = slide.src;
clearInterval(timer);
}
</script>
</body>
</html>