I'm taking a coding class at school and am very new to javascript, so hopefully what I'm asking will make sense!
Right now I have a page where if you click an html button, an image of a worm appears in a div below it (called "bugs"). the same image appears each time you click the button. I've done this by having the button click call a function that creates an img element and adds it as a child of the div. the issue is I want the images to move randomly around the page or even just inside the div. I've found some code that will animate a div so it moves randomly using jQuery (here), but I can't for the life of me figure out how to apply it to the images.
The js code that makes the images looks like this:
var BugSpace = document.getElementById("bugs");
function NewWorm(){
WormPic = document.createElement("img");
WormPic.src = "worm.png";
BugSpace.appendChild(WormPic);
};
Most of my code is pieced together from various tutorials so is likely pretty convoluted. anyway, if anyone can figure this out I'll be eternally grateful :~)
Edit: I suppose I should further clarify that the code includes two other buttons to make two other types of bugs! I'd like to be able to have a few images of each bug moving on the page at once. I figure the best way to do this is to find a way to animate the children of the "bug" div? I am, however, wondering if the answer to my problem might turn out to be a complete reworking of the code I have now!
If you're comfortable using jQuery, then you can use the following solution.
You basically still animate the
divand because theimgis contained within thediv, it will animate too.All you need to do is call the
animateDiv()function after you've added the image.The
animateDiv()function here is exactly the same as the link you've provided.Have a look at the jsfiddle: http://jsfiddle.net/3xgqogkk/
EDIT (based on more information from the comments)
So the new core javascript looks like:
Which means you have to make some modifications to the
animateDiv()method, which is now actuallyanimateDiv($worm)The important thing is to understand everything that's happening here, so if you have any questions, just ask :)
The jsfiddle is also updated: http://jsfiddle.net/3xgqogkk/