I want to make a simple button clicker that shows one manatee most of the time, more rarely shows two manatees, and even more rarely (1 in 100) shows three manatees.
But how do I connect the Javascript to a button in HTML and make new content appear below it each time it is clicked? I know very little about programming. Break it down very simply for my squidgy manatee brain. (•(°°)•)
First you need an element for the manatees to appear in. For this response, I’ll assume an element with id=manateesOut. I’ll use document.getElementById("manateesOut") to reference the element in the JavaScript. The element should have no content to start with.
Then replace each console.log() with a replacement of the element’s textContent, like so: document.getElementById("manateesOut").textContent="(•(°°)•)(•(°°)•)"; (or some other number of manatees)
If you want the manatees to be added to the existing content instead of replacing it, use += instead of =. (Note this will not put line breaks between the manatees. If you want line breaks, you can do something like document.getElementById("manateesOut").innerHTML+="<br>(•(°°)•)(•(°°)•)";.)
Put all the code that should be run on the button-click inside a function. For this response I’ll assume the function is called displayManatee().
Then in your HTML include a <button type=button onclick=displayManatee()>button text here</button>.
I took a crack at building a little proof-of-concept for what you’re trying to achieve. I jammed the code with a bunch of comments to try to make things easier to understand.
Hope this is useful! Click “Edit on Codepen” on the right to see it in full:
I’m in the UTC+8 timezone, but feel free to shoot me a message if you want help figuring anything out! I’ll reply as soon as I can, which may be in real time when our awake times line up.
define a function that updates the manatees which:
Gets container element by id (any empty container div which you want the manatees to show up in)
Gets random number
Updates container element text based on the number drawn
Then when you write your html, you should be able to do just attach that second function to your button via the onclick attribute.
Keeping all your code organised into small functions like this helps you see where everything should go; the order of the functions themselves doesn’t usually matter much, and the order of what’s inside each function should be easy to reason about (e.g., you can’t update the container contents before you’ve retrieved the container, so getElementById(‘manatee-out’) comes first).
I don’t have a whole lot to add here bc I’m not great at JS but this is a really good breakdown on how it works and I think it changed how I go about writing code !!! Thank you haha this is a great way to word it.