[vc_row][vc_column width=”2/3″][vc_separator][venera_framed_image content_type=”video” css_animation=”appear” frame_type=”browser” slider_engine=”flexslider” video_link=”https://www.youtube.com/watch?v=TLjJM-CsOIs” browser_url=”https://www.youtube.com/watch?v=TLjJM-CsOIs”][vc_separator][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row][vc_row][vc_column width=”2/3″][vc_tabs][vc_tab title=”About This Project” tab_id=”1402713028-1-39e9a4-2f88123b-77946048-9294″][vc_column_text]
Many people on the internet aren’t familiar with how to make a decent website on the internet. In an effort to remedy that, this episode kicks off the first of a five part series explaining the different aspects of building a good looking, database driven website from scratch.
In part 3 of this series, we will look at the basics of using Javascript and using it to enhance our site.
Here’s a list of the other tutorials in the series:
[/vc_column_text][/vc_tab][vc_tab title=”Code” tab_id=”1402753910272-3-8123b-77946048-9294″][vc_button title=”Download Code Sample” target=”_blank” icon=”none” size=”btn-huge” href=”http://www.tinkernut.com/demos/306_javascript/306_javascript.zip”][vc_column_text]
Javascript Syntax
To create a Javascript within an HTML file, you generally need to start with “Script” tags to mark the beginning and end of the script. Although not mentioned in the video, it’s a good habit to describe what type of script you are going to be invoking by using the type=”text/javascript” attribute, which you can see in the example below.
Though not required for simple scripts, it’s also a good idea to divide sections of your script into “blocks”, which are charactarized by opening and closing curly brackets. They are required for functions.
The lines in between the curly brackets are the Javascript code that is to be executed.
<script type="text/javascript"> { document.write('Hi! Welcome to my site'); } </script>
Not all browsers support Javascript. Because of this, there is a method to code your Javascript so that it doesn’t try to run on unsupported browsers. The syntax resemebles an arrow and is demonstrated below.
<script type="text/javascript"> <!-- { document.write('Hi! Welcome to my site'); } //--> </script>
ID’s
In order to keep Javascripts organized and in one location within your HTML, there needs to be a way to reference elements within the HTML code. When using CSS, this is done through an attribute called “class” that allows you to label the elements that you want to reference. Similarly, when using Javascript, you can use the “ID” attribute to label elements. The value of the ID can be whatever you want, but it’s common practice to use only letters and to make sure it is no longer than one word. In the example below, you see a paragraph element that has been given and ID of “mainText”:
<p id="mainText">This is my main text </p>
To call an ID from your Javascript code, you want to use the “document” function followed by “getElementById” and then the Id name in parenthesis and quotes. Here’s an example:
document.getElementById('mainText')
Following this format, you can call other functions such as “value” to return the value of the element, or “innerHTML”, which will overwrite the element with HTML code. You can find examples of both in the final code below.
Functions
A benefit of Javascript is that you can set aside blocks of code so that it only runs when it’s triggered. This is done through a coding process called “Functions”. Functions let you divide your code up into different sections that can be triggered by different events. To create a function, simply block the Javascript code you want to be in the function with curly brackets {} and before the first curly bracket type function and then the name of your function, which can be anything. The example below shows a script with two different functions within it.
<script type="text/javascript"> function changeText{ document.getElementById('mainText').innerHTML='Welcome to my data page!'; } function alertUser{ alert('This is an alert!'); } </script>
An important thing to note is that functions will not run unless there is something that executes or triggers it. A common way of triggering a function is through the “onClick” attribute, which can be added to HTML elements. This attribute makes it so that when a user clicks on an element, then the function will be executed. Here’s an example:
<p id="mainText" onClick="ChangeText">This is my main text </p>
Variables
A variable is an object within programming code that can change it’s value as the program is executed. It’s similar to mathmatics were variables are used in equations to represent unknown values i.e. 2 + x = 4. Variables are used very frequently in Javascript because their value can be set to whatever you need it to. To create a variable in Javascript, you need to declare the var object and then give the variable a name. Commonly x is used, but it can be whatever letter or word you want. After you have declared the variable, you can set it equal to a value. You can change the variables value as many times as you need to throughout the course of your script. Here is an example of a variable in use:
<script> var x; x = 'Daniel'; document.write('My name is ' + x); </script>
To make Javascript more concise, you can combine the variable declaration with it’s value declaration. Using the same example as above, here’s what the code would look like if you combined the two:
<script> var x = 'Gigafide'; document.write('My name is ' + x); </script>
Concatenation
To “concatenate” something means to join or combine two different object together (such as word strings). Each programming language has their own unique way to concatenate strings. In Javascript, we use the + sign. Concatenation is primarily used in displaying the results of something. Here’s what it looks like:
<script> var x = 'Gigafide'; var y = 'My name is '; document.write(y + x); </script>
The results of this code would be “My Name is Gigafide”.
Conditional Statements
When creating programs in Javascript, you often run across the need to display one of many possible outcomes or options. As an example, if you ask a “yes” or “no” question, you want to display different results depending on what the user answers. This is often accomplished through “conditional statements”. The most commonly used conditional statement in Javascript is the “If” statement
Operators
Common Javascripts
Linking to an external Javascript file
As with CSS, you can copy all of your code to an external document and link to it from your HTML. What would you want to do this? There’s two possible reasons. The first reason is that it is a good way to keep your HTML code clean and streamlined. The second reason is so that one Javascript can be used on multiple webpages. To create an external file, copy all of your Javascript code (between the <script> tags) to a new document and save it as myjavascript.js, or whatever you want to call it, and save it to the same directory as your index.html file. Then you can add this line to the head of your HTML document:
<script type="text/javascript" src="myjavascript.js"></script>
Dates and Times
Another common usage of Javascripting is to display a date or to use a date or time in a function. When dealing with the date function, it’s important to keep in mind that the time that is used is the time on the client/users computer and not the time on the server that your webpage is on. Displaying a date string is very simple. Just use the date object like this:
<script> document.write(Date()); </script>
If you want to display only the year or the date, you would need to assign a variable to the date object and then call either getFullYear(), getTime(), or getDay() depending on your need.
<script> var myDate=new Date(); document.write(myDate.getFullYear()); </script>
Cookies
Another useful aspect of Javascript is the ability to store script information on the clients computer. This stored infomration is known as a “cookie”. It’s general purpose is to store user information so that the user doesn’t have to enter in the same information again. For instance, websites commonly store a cookie of your username and password so that you don’t have to keep logging in to the website everytime you visit. Cookies can get very complicated but below you’ll find an example of a cookie that stores the users name and remembers it each time they visit a site. This example is taken from w3schools.com
Creating a cookie:
function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; }
Reading a cookie:
function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } }
Checking a cookie:
function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,365); } } }
Printing a page
Javascript provides a really simple way to print a web page. The script calls the browsers print function and uses it to print the webpage that the Javascript is on. All that’s required to invoke this script is the “onClick” attribute:
<form> <input type="button" value="Print This Page" onClick="window.print()" /> </form>
Page Redirect
“Redirecting” a page is a means of having a webpage auto-forward to a different webpage. A good reason to use this would be for if you are making changes to your web page and you want users to be redirected to a temporary page until your changes are finished.
<script type="text/javascript"> window.location = "http://www.google.com/" </script>
Final Code
After completeing the tutorial, you should have something similar to the code below. Please use this code for reference and correction. There are three files, the first one is index.html, which is the HTML code for the main page in your website. The second one is style.css, which is the CSS code referenced in the index.html webpage. don’t say
<html> <head> <title>My Data</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script> function clicked(){ var x; x = document.getElementById('nameCheck').value; if(x !=""){ document.getElementById('greeting').innerHTML='Hi, '+x+'! Welcome to my site!'; } else{ document.getElementById('errorMsg').innerHTML='<font color="red">(required) Name:</font>'; } } </script> </head> <body> <div class="main"> <div class="row1"> <img src="logo.jpg"/> </div> <div class="row2"> <div class="row2col1"> Navigation <hr align="left" width=75%> <ul> <li><a href="about.html">About Me</a></li> <li><a href="http://www.google.com">Google</a></li> </ul> </div> <div class="row2col2"><p class="welcome" id="greeting"> Hi! Welcome to my site! <form> <b id="errorMsg">Name:</b> <input type="text" id="nameCheck" /> <input type="button" value="Click Me" onClick="clicked()" /> </form> </p><p class="content" >This page is a work in progress that will eventually show places for data input, as well as data recall. Check back here for updates and more information! Thanks for visiting!</p> </div> </div> </div> </body> </html>
[/vc_column_text][/vc_tab][vc_tab title=”Important Links” tab_id=”1402753981900-3-10123b-77946048-9294″][vc_column_text] Help support my channel: http://www.patreon.com/tinkernut Follow Tinkernut! Google + Facebook Twitter [/vc_column_text][/vc_tab][/vc_tabs][/vc_column][vc_column width=”1/3″][/vc_column][/vc_row]
are we not getting 15 points for watching new tutorials on your website? it says it in http://www.tinkernut.com/register
Yea we are! I just got 15 points!
This is great.. Waiting for the 4th video (PHP)!!! 🙂
He already made a video about this on youtube, and this one is SO MUCH BETTER!!
PS
I will give you all a link to the sote that I am making when i m done!!
Great video and great series. Easy to understand and very well done. Keep up the good work, your videos are great.
I know. I knew a lot about HTML, but he taught me a bunch about javascript. He rocks.
so much coding my head hurts
Hey guys. Does anyone know how to make a form (in HTML) that will send me any information that a user types in? I want to make a file sharing site, but I want to know who is in it. If it could send me an E-Mail or even store it in another site. Thanks Guys!
that is php i think you should wait for the next tutorial 😉
Can’t wait for the PHP tutorial!
Where is Part 1 of this Tutorial? Anybody know?
never mind… I just found it. Duh
Cool post . Thank you for, writing on this blog page dude! I shall message you some time! I did not know that!
HELP! THE TEXT WONT CHANGE IN MY SCRIPT!
here it is:
My Data
function clicked(){
var x;
x= ‘Hello!‘;
document.getElementById(‘greeting’).innerHTML=’x’;
}
a{
text-decoration:none;
color:grey;
}
p.welcome{
font-family:”verdana”;
font-size:1.875em;
color:white;
text-align:center;
font-style:bold;
}
p.content{
font-family:”verdana”;
font-size:1em;
color:white;
text-align:center;
}
div.n00b{
width:50%;
margin:auto;
background:#251111;
}
div.side1{
float:left;
margin:0;
background:#251111;
}
div.side2{
margin-left:25%
background:#251111;
}
Hello
This page is still a work in progress, so there is still more to come. But make sure to check back every day to see the updates I did.
Tinkernut – the guy who helped me make this website
Google
whenever i click the button, “hello” doesnt change to “hello“
i meant the script to be typed like this because of tinkernut allowing HTML tags into descriptions
My Data
function clicked(){
var x;
x= ‘Hello!‘;
document.getElementById(‘greeting’).innerHTML=’x’;
}
a{
text-decoration:none;
color:grey;
}
p.welcome{
font-family:”verdana”;
font-size:1.875em;
color:white;
text-align:center;
font-style:bold;
}
p.content{
font-family:”verdana”;
font-size:1em;
color:white;
text-align:center;
}
div.n00b{
width:50%;
margin:auto;
background:#251111;
}
div.side1{
float:left;
margin:0;
background:#251111;
}
div.side2{
margin-left:25%
background:#251111;
}
Hello
This page is still a work in progress, so there is still more to come. But make sure to check back every day to see the updates I did.
Tinkernut – the guy who helped me make this website
Google