// Insert script element
var script = document.createElement(‘script’);
script.src = ‘externalScript.js’;
document.head.appendChild(script);

// Writing basic JavaScript code
var name = ‘John’;
var age = 25;
console.log(‘Name: ‘ + name);
console.log(‘Age: ‘ + age);

// Working with elements and events
var button = document.getElementById(‘myButton’);
button.addEventListener(‘click’, function() {
console.log(‘Button clicked’);
});

// Structuring JavaScript code (embedded vs external JavaScript file source)
// externalScript.js
function showMessage() {
console.log(‘Hello, world!’);
}
showMessage();

// Creating JavaScript functions
function addNumbers(a, b) {
return a + b;
}

// Calling a JavaScript function
var result = addNumbers(3, 5);
console.log(‘Result: ‘ + result);

// Parsing arguments to JS function
function greetUser(name) {
console.log(‘Hello, ‘ + name + ‘!’);
}
greetUser(‘Alice’);

// Handling events with functions
function handleButtonClick() {
console.log(‘Button clicked’);
}
button.addEventListener(‘click’, handleButtonClick);

// Working with Document Object Model (DOM)
var element = document.getElementById(‘myElement’);
console.log(‘Element content: ‘ + element.textContent);

!Changing Element Styles

var element = document.getElementById(‘myElement’);
element.style.color = ‘red’;
element.style.backgroundColor = ‘yellow’;

  1. Creating and appending new elements:

var newElement = document.createElement(‘div’);
newElement.textContent = ‘New element’;
document.body.appendChild(newElement);

 

  1. Form validation: 

var form = document.getElementById(‘myForm’);
form.addEventListener(‘submit’, function(event) {
var input = document.getElementById(‘myInput’);
if (input.value === ”) {
event.preventDefault();
console.log(‘Input cannot be empty’);
}
});

 

  1. AJAX request using fetch:

fetch(‘https://api.example.com/data’)
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(‘Error:’, error);
});

 

  1. Create forms and form fields:

<form id=”myForm”>
<!– Form fields go here –>
</form>

 

  1. Create labels and input fields:
<label for="name">Name:</label>
<input type="text" id="name" name="name">

  1. Work with date and time fields (widgets):

<label for=”date”>Date:</label>
<input type=”date” id=”date” name=”date”>

  1. Create a selection list:

<label for=”options”>Select an option:</label>
<select id=”options” name=”options”>
<option value=”option1″>Option 1</option>
<option value=”option2″>Option 2</option>
</select>

  1. Create option buttons (radio buttons):

<label>
<input type=”radio” name=”radioOptions” value=”option1″> Option 1
</label>
<label>
<input type=”radio” name=”radioOptions” value=”option2″> Option 2
</label>

 

  1. Create checkboxes and textarea:

<label>
<input type=”checkbox” name=”option1″ value=”option1″> Option 1
</label>
<label>
<input type=”checkbox” name=”option2″ value=”option2″> Option 2
</label>

<textarea id=”myTextarea” name=”myTextarea”></textarea>

 

  1. Use data lists:
<label for=”myInput”>Select an item:</label>
<input list=”myDataList” id=”myInput” name=”myInput”>
<datalist id=”myDataList”>
<option value=”Option 1″>
 value=”Option 2″>
<option value=”Option 3″>
</datalist><option

  1. Create form buttons:

<button type=”submit”>Submit</button>
<button type=”reset”>Reset</button>
<button type=”button”>Click Me</button>

  1. Understanding audio and video formats:

<audio controls>
<source src=”audio.mp3″ type=”audio/mpeg”>
<source src=”audio.ogg” type=”audio/ogg”>
Your browser does not support the audio element.
</audio>

       

  1. Insert an HTML video clip:

<video controls>
<source src=”video.mp4″ type=”video/mp4″>
<source src=”video.webm” type=”video/webm”>
Your browser does not support the video element.
</video>

 

The <input> Element

One of the most used form element is the <input> element.

The <input> element can be displayed in several ways, depending on the type attribute.

Example

<label for=”fname”>First name:</label>
<input type=”text” id=”fname” name=”fname”>

Try it Yourself »

All the different values of the type attribute are covered in the next chapter: HTML Input Types.


The <label> Element

The <label> element defines a label for several form elements.

The <label> element is useful for screen-reader users, because the screen-reader will read out loud the label when the user focus on the input element.

The <label> element also help users who have difficulty clicking on very small regions (such as radio buttons or checkboxes) – because when the user clicks the text within the <label> element, it toggles the radio button/checkbox.

The for attribute of the <label> tag should be equal to the id attribute of the <input> element to bind them together.


The <select> Element

The <select> element defines a drop-down list:

Example

<label for=”cars”>Choose a car:</label>
<select id=”cars” name=”cars”>
  <option value=”volvo”>Volvo</option>
  <option value=”saab”>Saab</option>
  <option value=”fiat”>Fiat</option>
  <option value=”audi”>Audi</option>
</select>

Try it Yourself »

The <option> elements defines an option that can be selected.

By default, the first item in the drop-down list is selected.

To define a pre-selected option, add the selected attribute to the option:

Example

<option value=”fiat” selected>Fiat</option>

Try it Yourself »

Visible Values:

Use the size attribute to specify the number of visible values:

Example

<label for=”cars”>Choose a car:</label>
<select id=”cars” name=”cars” size=”3″>
  <option value=”volvo”>Volvo</option>
  <option value=”saab”>Saab</option>
  <option value=”fiat”>Fiat</option>
  <option value=”audi”>Audi</option>
</select>

Try it Yourself »

Allow Multiple Selections:

Use the multiple attribute to allow the user to select more than one value:

Example

<label for=”cars”>Choose a car:</label>
<select id=”cars” name=”cars” size=”4″multiple>
  <option value=”volvo”>Volvo</option>
  <option value=”saab”>Saab</option>
  <option value=”fiat”>Fiat</option>
  <option value=”audi”>Audi</option>
</select>

Try it Yourself »


The <textarea> Element

The <textarea> element defines a multi-line input field (a text area):

Example

<textarea name=”message” rows=”10″ cols=”30″>
The cat was playing in the garden.
</textarea>

Try it Yourself »

The rows attribute specifies the visible number of lines in a text area.

The cols attribute specifies the visible width of a text area.

This is how the HTML code above will be displayed in a browser:

You can also define the size of the text area by using CSS:

Example

<textarea name=”message” style=”width:200px; height:600px;”>
The cat was playing in the garden.
</textarea>

 


The <button> Element

The <button> element defines a clickable button:

Example

<button type=”button” onclick=”alert(‘Hello World!’)”>Click Me!</button>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

Note: Always specify the type attribute for the button element. Different browsers may use different default types for the button element.


The <fieldset> and <legend> Elements

The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> element.

Example

<form action=”/action_page.php”>
  <fieldset>
    <legend>Personalia:</legend>
    <label for=”fname”>First name:</label><br>
    <input type=”text” id=”fname” name=”fname” value=”John”><br>
    <label for=”lname”>Last name:</label><br>
    <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
    <input type=”submit” value=”Submit”>
  </fieldset>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

Personalia:

First name:

Last name:


The <datalist> Element

The <datalist> element specifies a list of pre-defined options for an <input> element.

Users will see a drop-down list of the pre-defined options as they input data.

The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.

Example

<form action=”/action_page.php”>
  <input list=”browsers”>
  <datalist id=”browsers”>
    <option value=”Internet Explorer”>
    <option value=”Firefox”>
    <option value=”Chrome”>
    <option value=”Opera”>
    <option value=”Safari”>
  </datalist>
</form>

Try it Yourself »


The <output> Element

The <output> element represents the result of a calculation (like one performed by a script).

Example

Perform a calculation and show the result in an <output> element:

<form action=”/action_page.php”
  oninput=”x.value=parseInt(a.value)+parseInt(b.value)”
>

  0
  <input type=”range”  id=”a” name=”a” value=”50″>
  100 +
  <input type=”number” id=”b” name=”b” value=”50″>
  =
  <output name=”x” for=”a b”></output>
  <br><br>
  <input type=”submit”>
</form>

Input Type Text

<input type="text"> defines a single-line text input field:

Example

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:


Input Type Password

<input type="password"> defines a password field:

Example

<form>
  <label for=”username”>Username:</label><br>
  <input type=”text” id=”username” name=”username”><br>
  <label for=”pwd”>Password:</label><br>
  <input type=”password” id=”pwd” name=”pwd”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

Username:

Password:

The characters in a password field are masked (shown as asterisks or circles).


ADVERTISEMENT

Input Type Submit

<input type="submit"> defines a button for submitting form data to a form-handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form’s action attribute:

Example

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

If you omit the submit button’s value attribute, the button will get a default text:

Example

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit”>
</form>

Try it Yourself »


Input Type Reset

<input type="reset"> defines a reset button that will reset all form values to their default values:

Example

<form action=”/action_page.php”>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”><br><br>
  <input type=”submit” value=”Submit”>
  <input type=”reset”>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:
 

If you change the input values and then click the “Reset” button, the form-data will be reset to the default values.


Input Type Radio

<input type="radio"> defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:

Example

<p>Choose your favorite Web language:</p>

<form>
  <input type=”radio” id=”html” name=”fav_language” value=”HTML”>
  <label for=”html”>HTML</label><br>
  <input type=”radio” id=”css” name=”fav_language” value=”CSS”>
  <label for=”css”>CSS</label><br>
  <input type=”radio” id=”javascript” name=”fav_language” value=”JavaScript”>
  <label for=”javascript”>JavaScript</label>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

 
 
 


Input Type Checkbox

<input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example

<form>
  <input type=”checkbox” id=”vehicle1″ name=”vehicle1″ value=”Bike”>
  <label for=”vehicle1″> I have a bike</label><br>
  <input type=”checkbox” id=”vehicle2″ name=”vehicle2″ value=”Car”>
  <label for=”vehicle2″> I have a car</label><br>
  <input type=”checkbox” id=”vehicle3″ name=”vehicle3″ value=”Boat”>
  <label for=”vehicle3″> I have a boat</label>
</form>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:

 
 
 


Input Type Button

<input type="button"> defines a button:

Example

<input type=”button” onclick=”alert(‘Hello World!’)” value=”Click Me!”>

Try it Yourself »

This is how the HTML code above will be displayed in a browser:


Input Type Color

The <input type="color"> is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.

Example

<form>
  <label for=”favcolor”>Select your favorite color:</label>
  <input type=”color” id=”favcolor” name=”favcolor”>
</form>

Try it Yourself »


Input Type Date

The <input type="date"> is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”birthday”>Birthday:</label>
  <input type=”date” id=”birthday” name=”birthday”>
</form>

Try it Yourself »

You can also use the min and max attributes to add restrictions to dates:

Example

<form>
  <label for=”datemax”>Enter a date before 1980-01-01:</label>
  <input type=”date” id=”datemax” name=”datemax” max=”1979-12-31″><br><br>
  <label for=”datemin”>Enter a date after 2000-01-01:</label>
  <input type=”date” id=”datemin” name=”datemin” min=”2000-01-02″>
</form>

Try it Yourself »


Input Type Datetime-local

The <input type="datetime-local"> specifies a date and time input field, with no time zone.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”birthdaytime”>Birthday (date and time):</label>
  <input type=”datetime-local” id=”birthdaytime” name=”birthdaytime”>
</form>

Try it Yourself »


Input Type Email

The <input type="email"> is used for input fields that should contain an e-mail address.

Depending on browser support, the e-mail address can be automatically validated when submitted.

Some smartphones recognize the email type, and add “.com” to the keyboard to match email input.

Example

<form>
  <label for=”email”>Enter your email:</label>
  <input type=”email” id=”email” name=”email”>
</form>

Try it Yourself »


Input Type Image

The <input type="image"> defines an image as a submit button.

The path to the image is specified in the src attribute.

Example

<form>
<input type=”image” src=”img_submit.gif” alt=”Submit” width=”48″ height=”48″>
</form>

Try it Yourself »


Input Type File

The <input type="file"> defines a file-select field and a “Browse” button for file uploads.

Example

<form>
  <label for=”myfile”>Select a file:</label>
  <input type=”file” id=”myfile” name=”myfile”>
</form>

Try it Yourself »


Input Type Hidden

The <input type="hidden"> defines a hidden input field (not visible to a user).

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.

A hidden field often stores what database record that needs to be updated when the form is submitted.

Note: While the value is not displayed to the user in the page’s content, it is visible (and can be edited) using any browser’s developer tools or “View Source” functionality. Do not use hidden inputs as a form of security!

Example

<form>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <input type=”hidden” id=”custId” name=”custId” value=”3487″>
  <input type=”submit” value=”Submit”>
</form>

Try it Yourself »


Input Type Month

The <input type="month"> allows the user to select a month and year.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”bdaymonth”>Birthday (month and year):</label>
  <input type=”month” id=”bdaymonth” name=”bdaymonth”>
</form>

Try it Yourself »


Input Type Number

The <input type="number"> defines a numeric input field.

You can also set restrictions on what numbers are accepted.

The following example displays a numeric input field, where you can enter a value from 1 to 5:

Example

<form>
  <label for=”quantity”>Quantity (between 1 and 5):</label>
  <input type=”number” id=”quantity” name=”quantity” min=”1″ max=”5″>
</form>

Try it Yourself »


Input Restrictions

Here is a list of some common input restrictions:

Attribute Description
checked Specifies that an input field should be pre-selected when the page loads (for type=”checkbox” or type=”radio”)
disabled Specifies that an input field should be disabled
max Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min Specifies the minimum value for an input field
pattern Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step Specifies the legal number intervals for an input field
value Specifies the default value for an input field

You will learn more about input restrictions in the next chapter.

The following example displays a numeric input field, where you can enter a value from 0 to 100, in steps of 10. The default value is 30:

Example

<form>
  <label for=”quantity”>Quantity:</label>
  <input type=”number” id=”quantity” name=”quantity” min=”0″ max=”100″ step=”10″ value=”30″>
</form>

Try it Yourself »


Input Type Range

The <input type="range"> defines a control for entering a number whose exact value is not important (like a slider control). Default range is 0 to 100. However, you can set restrictions on what numbers are accepted with the minmax, and step attributes:

Example

<form>
  <label for=”vol”>Volume (between 0 and 50):</label>
  <input type=”range” id=”vol” name=”vol” min=”0″ max=”50″>
</form>

Try it Yourself »


Input Type Search

The <input type="search"> is used for search fields (a search field behaves like a regular text field).

Example

<form>
  <label for=”gsearch”>Search Google:</label>
  <input type=”search” id=”gsearch” name=”gsearch”>
</form>

Try it Yourself »


Input Type Tel

The <input type="tel"> is used for input fields that should contain a telephone number.

Example

<form>
  <label for=”phone”>Enter your phone number:</label>
  <input type=”tel” id=”phone” name=”phone” pattern=”[0-9]{3}-[0-9]{2}-[0-9]{3}”>
</form>

Try it Yourself »


Input Type Time

The <input type="time"> allows the user to select a time (no time zone).

Depending on browser support, a time picker can show up in the input field.

Example

<form>
  <label for=”appt”>Select a time:</label>
  <input type=”time” id=”appt” name=”appt”>
</form>

Try it Yourself »


Input Type Url

The <input type="url"> is used for input fields that should contain a URL address.

Depending on browser support, the url field can be automatically validated when submitted.

Some smartphones recognize the url type, and adds “.com” to the keyboard to match url input.

Example

<form>
  <label for=”homepage”>Add your homepage:</label>
  <input type=”url” id=”homepage” name=”homepage”>
</form>

Try it Yourself »


Input Type Week

The <input type="week"> allows the user to select a week and year.

Depending on browser support, a date picker can show up in the input field.

Example

<form>
  <label for=”week”>Select a week:</label>
  <input type=”week” id=”week” name=”week”>

The value Attribute

The input value attribute specifies an initial value for an input field:

Example

Input fields with initial (default) values:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John”><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”>
</form>

Try it Yourself »


The readonly Attribute

The input readonly attribute specifies that an input field is read-only.

A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).

The value of a read-only input field will be sent when submitting the form!

Example

A read-only input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John” readonly><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”>
</form>

Try it Yourself »


The disabled Attribute

The input disabled attribute specifies that an input field should be disabled.

A disabled input field is unusable and un-clickable.

The value of a disabled input field will not be sent when submitting the form!

Example

A disabled input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” value=”John” disabled><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname” value=”Doe”>
</form>

Try it Yourself »


ADVERTISEMENT

The size Attribute

The input size attribute specifies the visible width, in characters, of an input field.

The default value for size is 20.

Note: The size attribute works with the following input types: text, search, tel, url, email, and password.

Example

Set a width for an input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” size=”50″><br>
  <label for=”pin”>PIN:</label><br>
  <input type=”text” id=”pin” name=”pin” size=”4″>
</form>

Try it Yourself »


The maxlength Attribute

The input maxlength attribute specifies the maximum number of characters allowed in an input field.

Note: When a maxlength is set, the input field will not accept more than the specified number of characters. However, this attribute does not provide any feedback. So, if you want to alert the user, you must write JavaScript code.

Example

Set a maximum length for an input field:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” size=”50″><br>
  <label for=”pin”>PIN:</label><br>
  <input type=”text” id=”pin” name=”pin” maxlength=”4″ size=”4″>
</form>

Try it Yourself »


The min and max Attributes

The input min and max attributes specify the minimum and maximum values for an input field.

The min and max attributes work with the following input types: number, range, date, datetime-local, month, time and week.

Tip: Use the max and min attributes together to create a range of legal values.

Example

Set a max date, a min date, and a range of legal values:

<form>
  <label for=”datemax”>Enter a date before 1980-01-01:</label>
  <input type=”date” id=”datemax” name=”datemax” max=”1979-12-31″><br><br>  <label for=”datemin”>Enter a date after 2000-01-01:</label>
  <input type=”date” id=”datemin” name=”datemin” min=”2000-01-02″><br><br>  <label for=”quantity”>Quantity (between 1 and 5):</label>
  <input type=”number” id=”quantity” name=”quantity” min=”1″ max=”5″>
</form>

Try it Yourself »


The multiple Attribute

The input multiple attribute specifies that the user is allowed to enter more than one value in an input field.

The multiple attribute works with the following input types: email, and file.

Example

A file upload field that accepts multiple values:

<form>
  <label for=”files”>Select files:</label>
  <input type=”file” id=”files” name=”files” multiple>
</form>

Try it Yourself »


The pattern Attribute

The input pattern attribute specifies a regular expression that the input field’s value is checked against, when the form is submitted.

The pattern attribute works with the following input types: text, date, search, url, tel, email, and password.

Tip: Use the global title attribute to describe the pattern to help the user.

Tip: Learn more about regular expressions in our JavaScript tutorial.

Example

An input field that can contain only three letters (no numbers or special characters):

<form>
  <label for=”country_code”>Country code:</label>
  <input type=”text” id=”country_code” name=”country_code”
  pattern=”[A-Za-z]{3}” title=”Three letter country code”
>

</form>

Try it Yourself »


The placeholder Attribute

The input placeholder attribute specifies a short hint that describes the expected value of an input field (a sample value or a short description of the expected format).

The short hint is displayed in the input field before the user enters a value.

The placeholder attribute works with the following input types: text, search, url, tel, email, and password.

Example

An input field with a placeholder text:

<form>
  <label for=”phone”>Enter a phone number:</label>
  <input type=”tel” id=”phone” name=”phone”
  placeholder=”123-45-678″
  pattern=”[0-9]{3}-[0-9]{2}-[0-9]{3}”
>

</form>

Try it Yourself »


The required Attribute

The input required attribute specifies that an input field must be filled out before submitting the form.

The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

Example

A required input field:

<form>
  <label for=”username”>Username:</label>
  <input type=”text” id=”username” name=”username” required>
</form>

Try it Yourself »


The step Attribute

The input step attribute specifies the legal number intervals for an input field.

Example: if step=”3″, legal numbers could be -3, 0, 3, 6, etc.

Tip: This attribute can be used together with the max and min attributes to create a range of legal values.

The step attribute works with the following input types: number, range, date, datetime-local, month, time and week.

Example

An input field with a specified legal number intervals:

<form>
  <label for=”points”>Points:</label>
  <input type=”number” id=”points” name=”points” step=”3″>
</form>

Try it Yourself »

Note: Input restrictions are not foolproof, and JavaScript provides many ways to add illegal input. To safely restrict input, it must also be checked by the receiver (the server)!


The autofocus Attribute

The input autofocus attribute specifies that an input field should automatically get focus when the page loads.

Example

Let the “First name” input field automatically get focus when the page loads:

<form>
  <label for=”fname”>First name:</label><br>
  <input type=”text” id=”fname” name=”fname” autofocus><br>
  <label for=”lname”>Last name:</label><br>
  <input type=”text” id=”lname” name=”lname”>
</form>

Try it Yourself »


The height and width Attributes

The input height and width attributes specify the height and width of an <input type="image"> element.

Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded. Without these attributes, the browser does not know the size of the image, and cannot reserve the appropriate space to it. The effect will be that the page layout will change during loading (while the images load).

Example

Define an image as the submit button, with height and width attributes:

<form>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <input type=”image” src=”img_submit.gif” alt=”Submit” width=”48″ height=”48″>
</form>

Try it Yourself »


The list Attribute

The input list attribute refers to a <datalist> element that contains pre-defined options for an <input> element.

Example

An <input> element with pre-defined values in a <datalist>:

<form>
  <input list=”browsers”>
  <datalist id=”browsers”>
    <option value=”Internet Explorer”>
    <option value=”Firefox”>
    <option value=”Chrome”>
    <option value=”Opera”>
    <option value=”Safari”>
  </datalist>
</form>

Try it Yourself »


The autocomplete Attribute

The input autocomplete attribute specifies whether a form or an input field should have autocomplete on or off.

Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.

The autocomplete attribute works with <form> and the following <input> types: text, search, url, tel, email, password, datepickers, range, and color.

Example

An HTML form with autocomplete on, and off for one input field:

<form action=”/action_page.php” autocomplete=”on”>
  <label for=”fname”>First name:</label>
  <input type=”text” id=”fname” name=”fname”><br><br>
  <label for=”lname”>Last name:</label>
  <input type=”text” id=”lname” name=”lname”><br><br>
  <label for=”email”>Email:</label>
  <input type=”email” id=”email” name=”email” autocomplete=”off”><br><br>
  <input type=”submit” value=”Submit”>
</form>

he HTML <audio> Element

To play an audio file in HTML, use the <audio> element:

Example

<audio controls>
  <source src=”horse.ogg” type=”audio/ogg”>
  <source src=”horse.mp3″ type=”audio/mpeg”>
Your browser does not support the audio element.
</audio>

Try it Yourself »


HTML Audio – How It Works

The controls attribute adds audio controls, like play, pause, and volume.

The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.

The text between the <audio> and </audio> tags will only be displayed in browsers that do not support the <audio> element.


HTML <audio> Autoplay

To start an audio file automatically, use the autoplay attribute:

Example

<audio controls autoplay>
  <source src=”horse.ogg” type=”audio/ogg”>
  <source src=”horse.mp3″ type=”audio/mpeg”>
Your browser does not support the audio element.
</audio>

Try it Yourself »

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

Add muted after autoplay to let your audio file start playing automatically (but muted):

Example

<audio controls autoplay muted>
  <source src=”horse.ogg” type=”audio/ogg”>
  <source src=”horse.mp3″ type=”audio/mpeg”>
Your browser does not support the audio element.
</audio>

The HTML <video> Element

To show a video in HTML, use the <video> element:

Example

<video width=”320″ height=”240″ controls>
  <source src=”movie.mp4″ type=”video/mp4″>
  <source src=”movie.ogg” type=”video/ogg”>
Your browser does not support the video tag.
</video>

Try it Yourself »


How it Works

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are not set, the page might flicker while the video loads.

The <source> element allows you to specify alternative video files which the browser may choose from. The browser will use the first recognized format.

The text between the <video> and </video> tags will only be displayed in browsers that do not support the <video> element.


HTML <video> Autoplay

To start a video automatically, use the autoplay attribute:

Example

<video width=”320″ height=”240″ autoplay>
  <source src=”movie.mp4″ type=”video/mp4″>
  <source src=”movie.ogg” type=”video/ogg”>
Your browser does not support the video tag.
</video>

Try it Yourself »

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

Add muted after autoplay to let your video start playing automatically (but muted):

Example

<video width=”320″ height=”240″ autoplay muted>
  <source src=”movie.mp4″ type=”video/mp4″>
  <source src=”movie.ogg” type=”video/ogg”>
Your browser does not support the video tag.
</video>

Try it Yourself »

 

  1. Introduction to Functions A function is a block of reusable code that performs a specific task. It allows you to encapsulate a set of instructions and execute them whenever needed. Functions help in modularizing code, promoting code reuse, and improving code organization.
  2. Function Declaration In JavaScript, you can declare a function using the function keyword followed by the function name, parentheses for parameters (if any), and curly braces to define the function body.

Example:

javascript
function greet() {
console.log("Hello!");
}

In this example, the function greet does not take any parameters and simply logs “Hello!” to the console.

  1. Function Invocation To execute a function, you need to invoke or call it by using its name followed by parentheses.

Example:

javascript
greet(); // Outputs: Hello!

Calling the greet() function executes the code inside its function body, resulting in the message “Hello!” being logged to the console.

  1. Function Parameters and Arguments Functions can accept inputs called parameters, which act as placeholders for values that will be passed when invoking the function. These values are referred to as arguments.

Example:

javascript
function greet(name) {
console.log("Hello, " + name + "!");
}

In this updated greet function, a name parameter is defined. When invoking the function, you need to provide an argument for the name parameter.

javascript
greet("Alice"); // Outputs: Hello, Alice!
greet("Bob"); // Outputs: Hello, Bob!
  1. Return Statement Functions can produce a value or result using the return statement. The return statement terminates the function execution and returns a value back to the caller.

Example:

javascript
function add(a, b) {
return a + b;
}

The add function takes two parameters a and b and returns their sum. To capture the returned value, you can assign it to a variable or use it in expressions.

javascript
var result = add(2, 3);
console.log(result); // Outputs: 5
  1. Anonymous Functions and Function Expressions JavaScript also allows the creation of anonymous functions, which are functions without a specific name. They are often used as function expressions, where they are assigned to variables.

Example:

javascript
var greet = function(name) {
console.log("Hello, " + name + "!");
};

In this example, the function is assigned to the variable greet. You can then invoke it using the variable name followed by parentheses.

javascript
greet("Alice"); // Outputs: Hello, Alice!
  1. Arrow Functions ES6 introduced arrow functions, which provide a concise syntax for writing functions. They are especially useful for shorter function expressions.

Example:

javascript
var multiply = (a, b) => a * b;

The arrow function multiply takes two parameters a and b and returns their product. It does not require the function keyword, curly braces, or a return statement for a concise one-line function.

javascript
var result = multiply(2, 3);
console.log(result); // Outputs: 6
  1. Higher-Order Functions In JavaScript, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from functions. Functions that operate on other functions are called higher-order functions

Canvas Examples

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.

The markup looks like this:

<canvas id=”myCanvas” width=”200″ height=”100″></canvas>

Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.

Here is an example of a basic, empty canvas:

Example

<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #000000;”>
</canvas>

Try it Yourself »



Add a JavaScript

After creating the rectangular canvas area, you must add a JavaScript to do the drawing.

Here are some examples:

Draw a Line

Example

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.moveTo(00);
ctx.lineTo(200100);
ctx.stroke();
</script>

Try it Yourself »


Draw a Circle

Example

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.beginPath();
ctx.arc(95504002 * Math.PI);
ctx.stroke();
</script>

Try it Yourself »


Draw a Text

Example

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.font = “30px Arial”;
ctx.fillText(“Hello World”1050);
</script>

Try it Yourself »


Stroke Text

Example

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
ctx.font = “30px Arial”;
ctx.strokeText(“Hello World”1050);
</script>

Try it Yourself »


Draw Linear Gradient

Example

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
// Create gradient
var grd = ctx.createLinearGradient(002000);
grd.addColorStop(0“red”);
grd.addColorStop(1“white”);// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(101015080);
</script>

Try it Yourself »


Draw Circular Gradient

Example

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
// Create gradient
var grd = ctx.createRadialGradient(755059060100);
grd.addColorStop(0“red”);
grd.addColorStop(1“white”);// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(101015080);
</script>

Try it Yourself »


Draw Image

<script>
var c = document.getElementById(“myCanvas”);
var ctx = c.getContext(“2d”);
var img = document.getElementById(“scream”);
ctx.drawImage(img, 1010);
</script>

Try it Yourself »

What is SVG?

  • SVG stands for Scalable Vector Graphics
  • SVG is used to define graphics for the Web
  • SVG is a W3C recommendation

The HTML <svg> Element

The HTML <svg> element is a container for SVG graphics.

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.


Browser Support

The numbers in the table specify the first browser version that fully supports the <svg> element.

Element          
<svg> 4.0 9.0 3.0 3.2 10.1

SVG Circle

 

Example

<!DOCTYPE html>
<html>
<body><svg width=”100″ height=”100″>
  <circle cx=”50″ cy=”50″ r=”40″ stroke=”green” stroke-width=”4″ fill=”yellow” />
</svg></body>
</html>

Try it Yourself »


ADVERTISEMENT

SVG Rectangle

 

Example

<svg width=”400″ height=”100″>
  <rect width=”400″ height=”100″ style=”fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)” />
</svg>

Try it Yourself »


SVG Rounded Rectangle

 

Example

<svg width=”400″ height=”180″>
  <rect x=”50″ y=”20″ rx=”20″ ry=”20″ width=”150″ height=”150″
  style=”fill:red;stroke:black;stroke-width:5;opacity:0.5″ /
>

</svg>

Try it Yourself »


SVG Star

 

Example

<svg width=”300″ height=”200″>
  <polygon points=”100,10 40,198 190,78 10,78 160,198″
  style=”fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;” /
>

</svg>

Try it Yourself »


SVG Logo

SVG

Example

<svg height=”130″ width=”500″>
  <defs>
    <linearGradient id=”grad1″ x1=”0%” y1=”0%” x2=”100%” y2=”0%”>
      <stop offset=”0%” style=”stop-color:rgb(255,255,0);stop-opacity:1″ />
      <stop offset=”100%” style=”stop-color:rgb(255,0,0);stop-opacity:1″ />
    </linearGradient>
  </defs>
  <ellipse cx=”100″ cy=”70″ rx=”85″ ry=”55″ fill=”url(#grad1)” />
  <text fill=”#ffffff” font-size=”45″ font-family=”Verdana” x=”50″ y=”86″>SVG</text>
  Sorry, your browser does not support inline SVG.
</svg>

Try it Yourself »

 

The CSS position property is versatile and powerful. It allows to set or alter an element’s position. It has 4 possible values:

  • static (default value)
  • relative
  • absolute
  • fixed

It’s often used alongside the 4 coordinates properties:

  • left
  • right
  • top
  • bottom

#static

This is the default position value: static elements just follow the natural flow. They aren’t affected by any leftrighttop or bottom value.

#relative

When the position is set to relative, an element can move according to its current position.

<p>Well, Ja should know his own business, I thought, and so I grasped the spear and clambered up toward the red man as rapidly as I could - being so far removed from my simian ancestors as I am</p>
<p>I imagine the slow-witted sithic, as Ja called him, suddenly realized our intentions and that he was quite likely to lose all his meal instead of having it doubled as he had hoped</p>
<p>When he saw me clambering up that spear he let out a hiss that fairly shook the ground, and came charging after me at a terrific rate</p>
p{ border: 1px solid blue;}

Well, Ja should know his own business, I thought, and so I grasped the spear and clambered up toward the red man as rapidly as I could – being so far removed from my simian ancestors as I am

I imagine the slow-witted sithic, as Ja called him, suddenly realized our intentions and that he was quite likely to lose all his meal instead of having it doubled as he had hoped

When he saw me clambering up that spear he let out a hiss that fairly shook the ground, and came charging after me at a terrific rate

Let’s move the second paragraph:

<p>Well, Ja should know his own business, I thought, and so I grasped the spear and clambered up toward the red man as rapidly as I could - being so far removed from my simian ancestors as I am</p>
<p class="second">I imagine the slow-witted sithic, as Ja called him, suddenly realized our intentions and that he was quite likely to lose all his meal instead of having it doubled as he had hoped</p>
<p>When he saw me clambering up that spear he let out a hiss that fairly shook the ground, and came charging after me at a terrific rate</p>
.second{ position: relative; border-color: red; left: 20px; top: 10px;}

Well, Ja should know his own business, I thought, and so I grasped the spear and clambered up toward the red man as rapidly as I could – being so far removed from my simian ancestors as I am

I imagine the slow-witted sithic, as Ja called him, suddenly realized our intentions and that he was quite likely to lose all his meal instead of having it doubled as he had hoped

When he saw me clambering up that spear he let out a hiss that fairly shook the ground, and came charging after me at a terrific rate

The red paragraph has moved 20px from the left and 10px from the top, relative to its natural position, where it’s supposed to be.

Notice how the blue paragraphs haven’t moved at all. By using relative positioning, the red paragraph can freely move without disrupting the layout. The only thing out of place is itself. All the other elements don’t know that element has moved.

#absolute

When the position is set to absolute, an element can move according to the first positioned ancestor.

“Positioned?? What is a positioned element?”

positioned element is one whose position value is either relativeabsolute or fixed. So unless the position is not set or static, an element is positioned.

The characteristic of a positioned element is that it can act as a reference point for its child elements.

Let’s imagine a simple hierarchy:

<section>
  I'm in position relative.
  <p>
    I'm in position absolute!
  </p>
</section>
section {
  background: gold;
  height: 200px;
  padding: 10px;
  position: relative; /* This turns the <section> into a point of reference for the <p> */
}

p {
  background: limegreen;
  color: white;
  padding: 10px;
  position: absolute; /* This makes the <p> freely movable */
  bottom: 10px; /* 10px from the bottom */
  left: 20px; /* 20px from the left */
}
I’m in position relative.I’m in position absolute!

The yellow section has a height of 200px and its position set to relative, which turns it into a point of reference for all my child elements.

As the green paragraph’s position is set to absolute, it can freely move according to the yellow section. By setting both bottom and left values, it will move from the bottom left corner.

What happens if we set both left AND right?

If the width is not set, applying left: 0 and right: 0 will stretch the element across the whole width. It’s the equivalent of setting left: 0 and width: 100%.

If the width is set, then the right value is discarded.

#fixed

When the position is set to fixed, it acts like absolute: you can set left/right and top/bottom coordinates.

The only difference is that the point of reference is the viewport. It means that a fixed element won’t scroll with the page ; it is fixed on the screen.

Creating a Countdown Timer

Example

<!– Display the countdown timer in an element –>
<p id=”demo”></p><script>
// Set the date we’re counting down to
var countDownDate = new Date(“Jan 5, 2024 15:37:25”).getTime();
// Update the count down every 1 second
var x = setInterval(function() {  // Get today’s date and time
  var now = new Date().getTime();  // Find the distance between now and the count down date
  var distance = countDownDate – now;  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);  // Display the result in the element with id=”demo”
  document.getElementById(“demo”).innerHTML = days + “d “ + hours + “h “
  + minutes + “m “ + seconds + “s “;  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById(“demo”).innerHTML = “EXPIRED”;
  }
}, 1000);
</script>

Try it Yourself »

 

How To Create a Login Form

Step 1) Add HTML:

Add an image inside a container and add inputs (with a matching label) for each field. Wrap a <form> element around them to process the input. You can learn more about how to process input in our PHP tutorial.

Example

<form action=”action_page.php” method=”post”>
  <div class=”imgcontainer”>
    <img src=”img_avatar2.png” alt=”Avatar” class=”avatar”>
  </div>  <div class=”container”>
    <label for=”uname”><b>Username</b></label>
    <input type=”text” placeholder=”Enter Username” name=”uname” required>    <label for=”psw”><b>Password</b></label>
    <input type=”password” placeholder=”Enter Password” name=”psw” required>    <button type=”submit”>Login</button>
    <label>
      <input type=”checkbox” checked=”checked” name=”remember”> Remember me
    </label>
  </div>  <div class=”container” style=”background-color:#f1f1f1″>
    <button type=”button” class=”cancelbtn”>Cancel</button>
    <span class=”psw”>Forgot <a href=”#”>password?</a></span>
  </div>
</form>

Step 2) Add CSS:

Example

/* Bordered form */
form {
  border: 3px solid #f1f1f1;
}
/* Full-width inputs */
input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}/* Set a style for all buttons */
button {
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}/* Add a hover effect for buttons */
button:hover {
  opacity: 0.8;
}/* Extra style for the cancel button (red) */
.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}/* Center the avatar image inside this container */
.imgcontainer {
  text-align: center;
  margin: 24px 0 12px 0;
}/* Avatar image */
img.avatar {
  width: 40%;
  border-radius: 50%;
}

/* Add padding to containers */
.container {
  padding: 16px;
}

/* The “Forgot password” text */
span.psw {
  float: right;
  padding-top: 16px;
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
    display: block;
    float: none;
}
  .cancelbtn {
    width: 100%;
}
}

Try it Yourself »

 

How To Create a Sign Up Form

Step 1) Add HTML:

Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs (with a matching label) for each field:

Example

<form action=”action_page.php” style=”border:1px solid #ccc”>
  <div class=”container”>
    <h1>Sign Up</h1>
    <p>Please fill in this form to create an account.</p>
    <hr>    <label for=”email”><b>Email</b></label>
    <input type=”text” placeholder=”Enter Email” name=”email” required>    <label for=”psw”><b>Password</b></label>
    <input type=”password” placeholder=”Enter Password” name=”psw” required>    <label for=”psw-repeat”><b>Repeat Password</b></label>
    <input type=”password” placeholder=”Repeat Password” name=”psw-repeat” required>    <label>
      <input type=”checkbox” checked=”checked” name=”remember” style=”margin-bottom:15px”> Remember me
    </label>    <p>By creating an account you agree to our <a href=”#” style=”color:dodgerblue”>Terms & Privacy</a>.</p>

    <div class=”clearfix”>
      <button type=”button” class=”cancelbtn”>Cancel</button>
      <button type=”submit” class=”signupbtn”>Sign Up</button>
    </div>
  </div>
</form>


Step 2) Add CSS:

Example

{box-sizing: border-box}

/* Full-width input fields */
  input[type=text], input[type=password] {
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  display: inline-block;
  border: none;
  background: #f1f1f1;
}

input[type=text]:focus, input[type=password]:focus {
  background-color: #ddd;
  outline: none;
}

hr {
  border: 1px solid #f1f1f1;
  margin-bottom: 25px;
}

/* Set a style for all buttons */
button {
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
  opacity: 0.9;
}

button:hover {
  opacity:1;
}

/* Extra styles for the cancel button */
.cancelbtn {
  padding: 14px 20px;
  background-color: #f44336;
}

/* Float cancel and signup buttons and add an equal width */
.cancelbtn, .signupbtn {
  float: left;
  width: 50%;
}

/* Add padding to container elements */
.container {
  padding: 16px;
}

/* Clear floats */
.clearfix::after {
  content: “”;
  clear: both;
  display: table;
}

/* Change styles for cancel button and signup button on extra small screens */
@media screen and (max-width: 300px) {
  .cancelbtn, .signupbtn {
    width: 100%;
}
}

Try it Yourself »

How To Create a Checkout Form

Step 1) Add HTML

Use a <form> element to process the input. You can learn more about this in our PHP tutorial.

Example

<div class=”row”>
  <div class=”col-75″>
    <div class=”container”>
      <form action=”/action_page.php”>        <div class=”row”>
          <div class=”col-50″>
            <h3>Billing Address</h3>
            <label for=”fname”><i class=”fa fa-user”></i> Full Name</label>
            <input type=”text” id=”fname” name=”firstname” placeholder=”John M. Doe”>
            <label for=”email”><i class=”fa fa-envelope”></i> Email</label>
            <input type=”text” id=”email” name=”email” placeholder=”john@example.com”>
            <label for=”adr”><i class=”fa fa-address-card-o”></i> Address</label>
            <input type=”text” id=”adr” name=”address” placeholder=”542 W. 15th Street”>
            <label for=”city”><i class=”fa fa-institution”></i> City</label>
            <input type=”text” id=”city” name=”city” placeholder=”New York”>            <div class=”row”>
              <div class=”col-50″>
                <label for=”state”>State</label>
                <input type=”text” id=”state” name=”state” placeholder=”NY”>
              </div>
              <div class=”col-50″>
                <label for=”zip”>Zip</label>
                <input type=”text” id=”zip” name=”zip” placeholder=”10001″>
              </div>
            </div>
          </div>          <div class=”col-50″>
            <h3>Payment</h3>
            <label for=”fname”>Accepted Cards</label>
            <div class=”icon-container”>
              <i class=”fa fa-cc-visa” style=”color:navy;”></i>
              <i class=”fa fa-cc-amex” style=”color:blue;”></i>
              <i class=”fa fa-cc-mastercard” style=”color:red;”></i>
              <i class=”fa fa-cc-discover” style=”color:orange;”></i>
            </div>
            <label for=”cname”>Name on Card</label>
            <input type=”text” id=”cname” name=”cardname” placeholder=”John More Doe”>
            <label for=”ccnum”>Credit card number</label>
            <input type=”text” id=”ccnum” name=”cardnumber” placeholder=”1111-2222-3333-4444″>
            <label for=”expmonth”>Exp Month</label>
            <input type=”text” id=”expmonth” name=”expmonth” placeholder=”September”>            <div class=”row”>
              <div class=”col-50″>
                <label for=”expyear”>Exp Year</label>
                <input type=”text” id=”expyear” name=”expyear” placeholder=”2018″>
              </div>
              <div class=”col-50″>
                <label for=”cvv”>CVV</label>
                <input type=”text” id=”cvv” name=”cvv” placeholder=”352″>
              </div>
            </div>
          </div>        </div>
        <label>
          <input type=”checkbox” checked=”checked” name=”sameadr”> Shipping address same as billing
        </label>
        <input type=”submit” value=”Continue to checkout” class=”btn”>
      </form>
    </div>
  </div>

  <div class=”col-25″>
    <div class=”container”>
      <h4>Cart
        <span class=”price” style=”color:black”>
          <i class=”fa fa-shopping-cart”></i>
          <b>4</b>
        </span>
      </h4>
      <p><a href=”#”>Product 1</a> <span class=”price”>$15</span></p>
      <p><a href=”#”>Product 2</a> <span class=”price”>$5</span></p>
      <p><a href=”#”>Product 3</a> <span class=”price”>$8</span></p>
      <p><a href=”#”>Product 4</a> <span class=”price”>$2</span></p>
      <hr>
      <p>Total <span class=”price” style=”color:black”><b>$30</b></span></p>
    </div>
  </div>
</div>


ADVERTISEMENT

Step 2) Add CSS:

Use CSS Flexbox to create a responsive layout:

Example

.row {
  display: -ms-flexbox; /* IE10 */
  display: flex;
  -ms-flex-wrap: wrap; /* IE10 */
  flex-wrap: wrap;
  margin: 0 -16px;
}
.col-25 {
  -ms-flex: 25%; /* IE10 */
  flex: 25%;
}.col-50 {
  -ms-flex: 50%; /* IE10 */
  flex: 50%;
}.col-75 {
  -ms-flex: 75%; /* IE10 */
  flex: 75%;
}.col-25,
.col-50,
.col-75 {
  padding: 0 16px;
}.container {
  background-color: #f2f2f2;
  padding: 5px 20px 15px 20px;
  border: 1px solid lightgrey;
  border-radius: 3px;
}

input[type=text] {
  width: 100%;
  margin-bottom: 20px;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

label {
  margin-bottom: 10px;
  display: block;
}

.icon-container {
  margin-bottom: 20px;
  padding: 7px 0;
  font-size: 24px;
}

.btn {
  background-color: #04AA6D;
  color: white;
  padding: 12px;
  margin: 10px 0;
  border: none;
  width: 100%;
  border-radius: 3px;
  cursor: pointer;
  font-size: 17px;
}

.btn:hover {
  background-color: #45a049;
}

span.price {
  float: right;
  color: grey;
}

/* Responsive layout – when the screen is less than 800px wide, make the two columns stack on top of each other instead of next to each other (and change the direction – make the “cart” column go on top) */
@media (max-width: 800px) {
  .row {
    flex-direction: column-reverse;
}
  .col-25 {
    margin-bottom: 20px;
}
}

Try it Yourself »

How To Create a Contact Form

Step 1) Add HTML

Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs (with a matching label) for each field:

Example

<div class=”container”>
  <form action=”action_page.php”>    <label for=”fname”>First Name</label>
    <input type=”text” id=”fname” name=”firstname” placeholder=”Your name..”>    <label for=”lname”>Last Name</label>
    <input type=”text” id=”lname” name=”lastname” placeholder=”Your last name..”>    <label for=”country”>Country</label>
    <select id=”country” name=”country”>
      <option value=”australia”>Australia</option>
      <option value=”canada”>Canada</option>
      <option value=”usa”>USA</option>
    </select>    <label for=”subject”>Subject</label>
    <textarea id=”subject” name=”subject” placeholder=”Write something..” style=”height:200px”></textarea>    <input type=”submit” value=”Submit”>

  </form>
</div>


ADVERTISEMENT

Step 2) Add CSS:

Example

/* Style inputs with type=”text”, select elements and textareas */
input[type=text], select, textarea {
  width: 100%; /* Full width */
  padding: 12px; /* Some padding */ 
  border: 1px solid #ccc; /* Gray border */
  border-radius: 4px; /* Rounded borders */
  box-sizing: border-box; /* Make sure that padding and width stays in place */
  margin-top: 6px; /* Add a top margin */
  margin-bottom: 16px; /* Bottom margin */
  resize: vertical /* Allow the user to vertically resize the textarea (not horizontally) */
}
/* Style the submit button with a specific background color etc */
input[type=submit] {
  background-color: #04AA6D;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}/* When moving the mouse over the submit button, add a darker green color */
input[type=submit]:hover {
  background-color: #45a049;
}/* Add a background color and some padding around the form */
.container {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}

Try it Yourself »

 

How To Create a Social Login Form

Step 1) Add HTML:

Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs or social media links for each field:

Example

<div class=”container”>
  <form action=”/action_page.php”>
    <div class=”row”>
      <h2 style=”text-align:center”>Login with Social Media or Manually</h2>
      <div class=”vl”>
        <span class=”vl-innertext”>or</span>
      </div>      <div class=”col”>
        <a href=”#” class=”fb btn”>
          <i class=”fa fa-facebook fa-fw”></i> Login with Facebook
        </a>
        <a href=”#” class=”twitter btn”>
          <i class=”fa fa-twitter fa-fw”></i> Login with Twitter
        </a>
        <a href=”#” class=”google btn”>
          <i class=”fa fa-google fa-fw”></i> Login with Google+
        </a>
      </div>      <div class=”col”>
        <div class=”hide-md-lg”>
          <p>Or sign in manually:</p>
        </div>        <input type=”text” name=”username” placeholder=”Username” required>
        <input type=”password” name=”password” placeholder=”Password” required>
        <input type=”submit” value=”Login”>
      </div>    </div>
  </form>
</div>

<div class=”bottom-container”>
  <div class=”row”>
    <div class=”col”>
      <a href=”#” style=”color:white” class=”btn”>Sign up</a>
    </div>
    <div class=”col”>
      <a href=”#” style=”color:white” class=”btn”>Forgot password?</a>
    </div>
  </div>
</div>


ADVERTISEMENT

Step 2) Add CSS:

Example

{box-sizing: border-box}

/* style the container */
.container {
  position: relative;
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px 0 30px 0;
}

/* style inputs and link buttons */
input,
.btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 4px;
  margin: 5px 0;
  opacity: 0.85;
  display: inline-block;
  font-size: 17px;
  line-height: 20px;
  text-decoration: none; /* remove underline from anchors */
}

input:hover,
.btn:hover {
  opacity: 1;
}

/* add appropriate colors to fb, twitter and google buttons */
.fb {
  background-color: #3B5998;
  color: white;
}

.twitter {
  background-color: #55ACEE;
  color: white;
}

.google {
  background-color: #dd4b39;
  color: white;
}

/* style the submit button */
input[type=submit] {
  background-color: #04AA6D;
  color: white;
  cursor: pointer;
}

input[type=submit]:hover {
  background-color: #45a049;
}

/* Two-column layout */
.col {
  float: left;
  width: 50%;
  margin: auto;
  padding: 0 50px;
  margin-top: 6px;
}

/* Clear floats after the columns */
.row:after {
  content: “”;
  display: table;
  clear: both;
}

/* vertical line */
.vl {
  position: absolute;
  left: 50%;
  transform: translate(-50%);
  border: 2px solid #ddd;
  height: 175px;
}

/* text inside the vertical line */
.inner {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #f1f1f1;
  border: 1px solid #ccc;
  border-radius: 50%;
  padding: 8px 10px;
}

/* hide some text on medium and large screens */
.hide-md-lg {
  display: none;
}

/* bottom container */
.bottom-container {
  text-align: center;
  background-color: #666;
  border-radius: 0px 0px 4px 4px;
}

/* Responsive layout – when the screen is less than 650px wide, make the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 650px) {
  .col {
    width: 100%;
    margin-top: 0;
  
}
  /* hide the vertical line */
  .vl {
    display: none;
  
}
  /* show the hidden text on small screens */
  .hide-md-lg {
    display: block;
    text-align: center;
  
}
}

How To Create a Register Form

Step 1) Add HTML:

Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs (with a matching label) for each field:

Example

<form action=”action_page.php”>
  <div class=”container”>
    <h1>Register</h1>
    <p>Please fill in this form to create an account.</p>
    <hr>    <label for=”email”><b>Email</b></label>
    <input type=”text” placeholder=”Enter Email” name=”email” id=”email” required>    <label for=”psw”><b>Password</b></label>
    <input type=”password” placeholder=”Enter Password” name=”psw” id=”psw” required>    <label for=”psw-repeat”><b>Repeat Password</b></label>
    <input type=”password” placeholder=”Repeat Password” name=”psw-repeat” id=”psw-repeat” required>
    <hr>

    <p>By creating an account you agree to our <a href=”#”>Terms & Privacy</a>.</p>
    <button type=”submit” class=”registerbtn”>Register</button>
  </div>

  <div class=”container signin”>
    <p>Already have an account? <a href=”#”>Sign in</a>.</p>
  </div>
</form>


ADVERTISEMENT

Step 2) Add CSS:

Example

{box-sizing: border-box}

/* Add padding to containers */
.container {
  padding: 16px;
}

/* Full-width input fields */
input[type=text], input[type=password] {
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  display: inline-block;
  border: none;
  background: #f1f1f1;
}

input[type=text]:focus, input[type=password]:focus {
  background-color: #ddd;
  outline: none;
}

/* Overwrite default styles of hr */
hr {
  border: 1px solid #f1f1f1;
  margin-bottom: 25px;
}

/* Set a style for the submit/register button */
.registerbtn {
  background-color: #04AA6D;
  color: white;
  padding: 16px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
  opacity: 0.9;
}

.registerbtn:hover {
  opacity:1;
}

/* Add a blue text color to links */
{
  color: dodgerblue;
}

/* Set a grey background color and center the text of the “sign in” section */
.signin {
  background-color: #f1f1f1;
  text-align: center;
}

How To Create an Icon Form

Step 1) Add HTML:

Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs for each field:

Example

<form action=”/action_page.php”>
  <h2>Register Form</h2>
  <div class=”input-container”>
    <i class=”fa fa-user icon”></i>
    <input class=”input-field” type=”text” placeholder=”Username” name=”usrnm”>
  </div>  <div class=”input-container”>
    <i class=”fa fa-envelope icon”></i>
    <input class=”input-field” type=”text” placeholder=”Email” name=”email”>
  </div>  <div class=”input-container”>
    <i class=”fa fa-key icon”></i>
    <input class=”input-field” type=”password” placeholder=”Password” name=”psw”>
  </div>  <button type=”submit” class=”btn”>Register</button>
</form>


ADVERTISEMENT

Step 2) Add CSS:

Example

{box-sizing: border-box;}

/* Style the input container */
.input-container {
  display: flex;
  width: 100%;
  margin-bottom: 15px;
}

/* Style the form icons */
.icon {
  padding: 10px;
  background: dodgerblue;
  color: white;
  min-width: 50px;
  text-align: center;
}

/* Style the input fields */
.input-field {
  width: 100%;
  padding: 10px;
  outline: none;
}

.input-field:focus {
  border: 2px solid dodgerblue;
}

/* Set a style for the submit button */
.btn {
  background-color: dodgerblue;
  color: white;
  padding: 15px 20px;
  border: none;
  cursor: pointer;
  width: 100%;
  opacity: 0.9;
}

.btn:hover {
  opacity: 1;
}

How To Create a Newsletter

Step 1) Add HTML

Use a <form> element to process the input. You can learn more about this in our PHP tutorial. Then add inputs for each field, together with a “submit” button:

Example

<form action=”action_page.php”>
  <div class=”container”>
    <h2>Subscribe to our Newsletter</h2>
    <p>Lorem ipsum..</p>
  </div>  <div class=”container” style=”background-color:white”>
    <input type=”text” placeholder=”Name” name=”name” required>
    <input type=”text” placeholder=”Email address” name=”mail” required>
    <label>
      <input type=”checkbox” checked=”checked” name=”subscribe”> Daily Newsletter
    </label>
  </div>  <div class=”container”>
    <input type=”submit” value=”Subscribe”>
  </div>
</form>


ADVERTISEMENT

Step 2) Add CSS:

Example

/* Style the form element with a border around it */
form {
  border: 4px solid #f1f1f1;
}
/* Add some padding and a grey background color to containers */
.container {
  padding: 20px;
  background-color: #f1f1f1;
}/* Style the input elements and the submit button */
input[type=text], input[type=submit] {
  width: 100%;
  padding: 12px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

/* Add margins to the checkbox */
input[type=checkbox] {
  margin-top: 16px;
}

/* Style the submit button */
input[type=submit] {
  background-color: #04AA6D;
  color: white;
  border: none;
}

input[type=submit]:hover {
  opacity: 0.8;
}

How To Create a Popup Form

Step 1) Add HTML

Use a <form> element to process the input. You can learn more about this in our PHP tutorial.

Example

<!– A button to open the popup form –>
<button class=”open-button” onclick=”openForm()”>Open Form</button><!– The form –>
<div class=”form-popup” id=”myForm”>
  <form action=”/action_page.php” class=”form-container”>
    <h1>Login</h1>

    <label for=”email”><b>Email</b></label>
    <input type=”text” placeholder=”Enter Email” name=”email” required>

    <label for=”psw”><b>Password</b></label>
    <input type=”password” placeholder=”Enter Password” name=”psw” required>

    <button type=”submit” class=”btn”>Login</button>
    <button type=”button” class=”btn cancel” onclick=”closeForm()”>Close</button>
  </form>
</div>


ADVERTISEMENT

Step 2) Add CSS:

Example

{box-sizing: border-box;}

/* Button used to open the contact form – fixed at the bottom of the page */
.open-button {
  background-color: #555;
  color: white;
  padding: 16px 20px;
  border: none;
  cursor: pointer;
  opacity: 0.8;
  position: fixed;
  bottom: 23px;
  right: 28px;
  width: 280px;
}

/* The popup form – hidden by default */
.form-popup {
  display: none;
  position: fixed;
  bottom: 0;
  right: 15px;
  border: 3px solid #f1f1f1;
  z-index: 9;
}

/* Add styles to the form container */
.form-container {
  max-width: 300px;
  padding: 10px;
  background-color: white;
}

/* Full-width input fields */
.form-container input[type=text], .form-container input[type=password] {
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  border: none;
  background: #f1f1f1;
}

/* When the inputs get focus, do something */
.form-container input[type=text]:focus, .form-container input[type=password]:focus {
  background-color: #ddd;
  outline: none;
}

/* Set a style for the submit/login button */
.form-container .btn {
  background-color: #04AA6D;
  color: white;
  padding: 16px 20px;
  border: none;
  cursor: pointer;
  width: 100%;
  margin-bottom:10px;
  opacity: 0.8;
}

/* Add a red background color to the cancel button */
.form-container .cancel {
  background-color: red;
}

/* Add some hover effects to buttons */
.form-container .btn:hover, .open-button:hover {
  opacity: 1;
}


Step 3) Add JavaScript:

Example

function openForm() {
  document.getElementById(“myForm”).style.display = “block”;
}
function closeForm() {
  document.getElementById(“myForm”).style.display = “none”;
}

 

How To Create a Responsive Form

Step 1) Add HTML

Use a <form> element to process the input. You can learn more about this in our PHP tutorial.

Add inputs (with a matching label) for each field, and wrap a <div> element around each label and input to set a specified width with CSS:

Example

<div class=”container”>
  <form action=”action_page.php”>
    <div class=”row”>
      <div class=”col-25″>
        <label for=”fname”>First Name</label>
      </div>
      <div class=”col-75″>
        <input type=”text” id=”fname” name=”firstname” placeholder=”Your name..”>
      </div>
    </div>
    <div class=”row”>
      <div class=”col-25″>
        <label for=”lname”>Last Name</label>
      </div>
      <div class=”col-75″>
        <input type=”text” id=”lname” name=”lastname” placeholder=”Your last name..”>
      </div>
    </div>
    <div class=”row”>
      <div class=”col-25″>
        <label for=”country”>Country</label>
      </div>
      <div class=”col-75″>
        <select id=”country” name=”country”>
          <option value=”australia”>Australia</option>
          <option value=”canada”>Canada</option>
          <option value=”usa”>USA</option>
        </select>
      </div>
    </div>
    <div class=”row”>
      <div class=”col-25″>
        <label for=”subject”>Subject</label>
      </div>
      <div class=”col-75″>
        <textarea id=”subject” name=”subject” placeholder=”Write something..” style=”height:200px”></textarea>
      </div>
    </div>
    <div class=”row”>
      <input type=”submit” value=”Submit”>
    </div>
  </form>
</div>

ADVERTISEMENT

Step 2) Add CSS:

Example

/* Style inputs, select elements and textareas */
input[type=text], select, textarea{
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  resize: vertical;
}
/* Style the label to display next to the inputs */
label {
  padding: 12px 12px 12px 0;
  display: inline-block;
}

/* Style the submit button */
input[type=submit] {
  background-color: #04AA6D;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  float: right;
}

/* Style the container */
.container {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
}

/* Floating column for labels: 25% width */
.col-25 {
  float: left;
  width: 25%;
  margin-top: 6px;
}

/* Floating column for inputs: 75% width */
.col-75 {
  float: left;
  width: 75%;
  margin-top: 6px;
}

/* Clear floats after the columns */
.row:after {
  content: “”;
  display: table;
  clear: both;
}

/* Responsive layout – when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .col-25, .col-75, input[type=submit] {
    width: 100%;
    margin-top: 0;
}
}

How To Create a Stacked Form

Step 1) Add HTML

Use a <form> element to process the input. You can learn more about this in our PHP tutorial.

Add inputs (with a matching label) for each field:

Example

 <form action=”/action_page.php”>
  <label for=”fname”>First Name</label>
  <input type=”text” id=”fname” name=”firstname” placeholder=”Your name..”>  <label for=”lname”>Last Name</label>
  <input type=”text” id=”lname” name=”lastname” placeholder=”Your last name..”>

  <label for=”country”>Country</label>
  <select id=”country” name=”country”>
    <option value=”australia”>Australia</option>
    <option value=”canada”>Canada</option>
    <option value=”usa”>USA</option>
  </select>

  <input type=”submit” value=”Submit”>
</form>


ADVERTISEMENT

Step 2) Add CSS:

Example

/* Style inputs */
  input[type=text], select {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
/* Style the submit button */
input[type=submit] {
  width: 100%;
  background-color: #04AA6D;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* Add a background color to the submit button on mouse-over */
input[type=submit]:hover {
  background-color: #45a049;
}