How I learned to use the <select> tag in HTML
So itās my third week in my coding boot-camp and itās project week. A very exciting yet nerve wrecking time. I feel like Iām playing catch-up every single day leading up to our project week. We get assigned our project groups and weāre set free to do our work. A few days later, I wanted our project site to be able to change background images with a simple button and event listener, but sometimes life isnāt so simple. I spent a few hours trying to grab my HTMLs document Body but miserably failed as I added a clickable button to change the ābackground-image: url(āā)ā. Iām sure thereās a way to handle that change through a button, but I went a different route. I found theĀ ā<select>ā tag method in HTML.Ā
Letās dissect this picture of code.(above)
<select> </select> Ā Ā (pictured above) Ā The select tag, by itself, creates this clickable drop-down arrow. Ā Inside of <select>, we want to add theĀ āonchangeā attribute which will trigger every-time thereās a change. So, we added a function we wanted triggered(more on this later).Ā Now that we have our dropdown arrow, we add our options with Ā <option></option>Ā (pictured below)
Each option here will add a selectable tile in our dropdown menu. The white letters in the picture above will be what is visible to the user. TheĀ āvalueā is what is important to us here, these are the paths we are going to use for our background images. When the user selects 1 of the 4 options, what weāre paying attention to is theĀ āvalueā.Ā Next Step
Recall thatĀ āonchangeā is inside the openingĀ ā<select>ā tag and will trigger every time there is a change. Now that we know that, we create a function to be called. In this case we called itĀ āhandleOnChangeEventā and it will pass the value of whichever selection is made. Now, letās look at the function. (picture below)
(This function is inside of Javascript) First, document.body.style.backgroundImage, will go into the styling of the background image inside of āBodyā, where we will need to place a path inside the parenthesis of āurlā. Second, this function will passĀ āxā, which is just a placeholder for the information (value) inside of our options, into the parentheses ofĀ āurlā.Ā
So now, in summary, when there is a selection made by our user, the value inside the parentheses of āurlā will be replaced by the value of whichever selection has been made. Thus, allowing the user to change the background image with a simple dropdown selection, which we have provided. Holy-smokes that was a lot! I hope this explanation helps somebody out there thatās as lost as I was in that moment. You can definitely try and mess around with the <selection> tag and add different functionalities to your functions. Anyways, thanks for reading! Ā
















