Can I change the tags in the HTML head with javascript? Especially the title tag?

Prepare

I simply want to be able to write something in an input element, push a button et voila! New page title!

Plan

I’m going to make a simple form. With an input element and a button. That’s it. A few lines of html.

The I have to figure out how I can grab the content of the input element with javascript and use it inside a function to change the page title.

I don’t want to use jQuery for this.

In the end, I will style it fancy shmancy with CSS.

Perform

The HTML

The HTML is simple. A container div, an input element with type of text, a label and a button.

The javascript

To get the input value I used getElementById. I keep forgetting to put document in front of getElementByID… so i get these “not defined blablabla” error messages. To get the content from the input you just use the value attribute. Like this getElementById(“some element”).value (stackoverflow). 

I saved the new title from the input in a variable called newTitle.

To get the title in the head I was thinking about getElementByTagName at first, but document.title was enough. I figured I could have the function set the new title like this: document.title = newTitle.

At first I had some problems. It wouldn’t grab the new title from the input box. To check if the function worked I made it return console.log(“Title Changed”). And to check if document.title = “new title” worked. I set it to something static. It worked.

So why wouldn’t it grab the content from the input box?

I tried to put it inside the console.log. It did not show. The function fired, sure enough. But no new title..

Then I found the answer on stackoverflow. I had the variable where i grabbed the value of the input, outside of my function. This causes it’s value to be null, since it is grabben when the document loads. Learned something new!

The CSS

So, to make the div round, with the content centered. I had some trouble. I found that you could just set the border-radius in percentages. Remember the width of the div when you do this!

At first i made an inner div, and set a margin to get it completely centered. But then I decide to make the div oval. And that was even simpler.

To get the shadows I got some help from cssmatics shadow generator.

The colors of the site itself are inspired by the colors from MDN.

To remove the blue glowing highlight from the input and the button I used the pseudo class :focus and set outline to none. I don’t know much about accessibility yet, but I guess this would be bad for it. I just wanted to try it out.

To change the background color on the button when it is click I used the pseudo class :active

And thats that! I very simple project. But even with this small and simple I learned something. And I could bet a lot of money on me remembering more from this, than from many of the courses I’ve “seen”.

To the project!