Disappearing Act

Jen tracy
2 min readFeb 17, 2021

One of the most wonderful (and terrifying) things about Javascript is that there is about a million was to do any given task. When I first started learning js this truly threw me for a loop before I realized how magical and freeing it could really be. To illustrate that there are multiple ways to accomplish the same thing I’m going to perform a magic trick.

I’m going to show you two ways to pull a rabbit out of a hat. The first way I’m going to accomplish this is by adding both images into my HTML then using CSS to stack the images on top of each other.

Notice that the bunny image in the css is positioned absolute and set all the way to the top left. This in combination with the div and hat image being relative to the rabbit image and the z-index at 1 makes it appear that the page only has a picture of a hat on it.

The next step is my favorite part Event Listeners! When you click on the picture of the hat it triggers another function. This function handles the event of the clique. Upon clicking on the image the hat image is now re-assigned a new id of "hidden-hat”. This simple triggers the css for that id which sets the image to hidden, and voila! The Rabbit(which was actually there the whole time) is now visible.

Another way to accomplish this is to replace the source code within the JavaScript after the click.

Although this approach is much quicker and takes far less CSS I personally prefer the first example. With the second approach the alt and class now don't match the image, so you would need to correct that manually within your js. and if you wanted to put the rabbit back in the hat you just made a lot more work for yourself.

but the first example if you put another event listener on the rabbit image you could set the id = “” and you have your hat back!

--

--