Forum Moderators: open

Message Too Old, No Replies

How to call a Javascript function within a DIV

javascript, html, css

         

abacus2011

5:18 pm on Sep 14, 2011 (gmt 0)

10+ Year Member



I have a simple task but cannot find a simple answer.

If I have an image slider defined as slideit() in javascript and I want that slider and its images to appear in a "DIV" how do I call that funstion or place it in the div.

I dont want it just in the <body> of the html I want to make the slider appear and work in a DIV.


//I would preload images in the head of the html
<html>
<head>
<script type="text/javascript">
var image1=new Image()
image1.src="image1.jpg"
var image2=new Image()
image2.src="image2.jpg"
</script>
</head>

<body>

//this is when I dont know where to put all this so it would appear in a div


//this laods the first image I assume this needs to be in the div tag
<img src="image1.jpg" name="slide" width=100 height=100>
//then the script i just need to alternate 2 images
<script type="text/javascript>
var step=function slideit(){
if(!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if(step<2)
step++
else step=1
steTimeout("slideit()",2500)
}
slideit()
</script>

birdbrain

9:09 pm on Sep 14, 2011 (gmt 0)



Hi there abacus2011,

try it like this...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">

<title>untitled document</title>

<style type="text/css">
#slide {
display:block;
width:100px;
height:100px;
border:1px solid #000;
margin:auto;
}
</style>

<script type="text/javascript">

var c=0;
var delay=2500;
var preloads=[];


function preload(){

for(var i=0;i<arguments.length;i++) {
preloads[preloads.length]=new Image();
preloads[preloads.length-1].src=arguments[i];
}
}

preload('image1.jpg','image2.jpg');

function slideit(){
document.getElementById('slide').src=preloads[c].src;
c++;
if(c==preloads.length) {
c=0;
}
setTimeout(function(){slideit()},delay);
}
window.addEventListener?
window.addEventListener('load',slideit,false):
window.attachEvent('onload',slideit);

</script>

</head>
<body>

<div>
<img id="slide" src="image1.jpg" alt="">
</div>

</body>
</html>

birdbrain

abacus2011

3:11 am on Sep 15, 2011 (gmt 0)

10+ Year Member



This works and clearly shows how to launch it in the div, thanks so much!

birdbrain

8:05 am on Sep 15, 2011 (gmt 0)



No problem, you're very welcome. ;)