Step 1: HTML
This is an example of plain old HTML code. Notice how it declares its doctype at the very top and has <head> and <body> sections enclosed in <html> opening and closing tags. The head section usually contains information about the page- like what its tab in a browser should say at the top, or what stylesheets the page is linked to. This particular code contains only two items, a large <h1> header, and a button. Viewed in a browser, the page looks like this:
Step 2: Linking HTML with CSS
This is where the <head> section comes in handy! In this section, we’re going to tell our html document to get its style elements from an external css document, as shown in the code below:
In this case, the href value inside the <link> tag is pointing to a file called css_sample_file.css within the same directory as our html file. At this point, our html file still looks the way it did in step 1, but now we can begin to make it prettier using CSS stored in the file we linked to.
Step 3: CSS Styling
This is an example of CSS code. Notice how on line 11 there’s a selector (in this case pointing to the button element in our html file), followed by open and close curly brackets. Within these brackets are a bunch of different style elements that we want the button to have — for example, we’ve changed the background color to a bright pink color and made the button round by increasing its border-radius attribute. With this styling (and some styling on the body and h1 elements of this page, along with an external font from google fonts API), our html document looks like this when we open it in the browser:
This code goes below my closing html tag. In my function, I use the getElementById function to grab the h1 element, whose id has been set to “title” within the <h1> tags shown in the previous HTML example. The rest of the function just says to change that element’s color to #003366 (the same as the background color). Now all that’s left is to link this function to our button!
Step 5: Putting it all together!
And that’s it! Now when I open the HTML file in my browser and click the button, my h1 text will seem to disappear.
Although this example of button functionality is kind of silly and useless, you can use the same concept to make a button execute whatever type of function you want. There are even built-in button functions, such as onClick= ‘history.go(0)’, that are designed to have specific purposes on live sites (in this case, refresh). Happy coding!