Understanding the JavaScript Syntax The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. A JavaScript consists of JavaScript statements that are placed within the <script></script> HTML tags in a web page, or within the external JavaScript file having .js extension. The following example shows how JavaScript statements look like: Example You will learn what each of these statements means in upcoming chapters. Case Sensitivity in JavaScript JavaScript is case-sensitive. This means that variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters. For example, the variable myVar must be typed myVar not MyVar or myvar. Similarly, the method name getElementById() must be typed with the exact case not as getElementByID(). Example If you checkout the browser console by pressing the f12 key on the keyboard, you’ll see a line something like this: “Uncaught ReferenceError: MyVar is not defined”. JavaScript Comments A comment is simply a line of text that is completely ignored by the JavaScript interpreter. Comments are usually added with the purpose of providing extra information pertaining to source code. It will not only help you understand your code when you look after a period of time but also others who are working with you on the same project. JavaScript support single-line as well as multi-line comments. Single-line comments begin with a double forward slash (//), followed by the comment text. Here’s an example: Example Whereas, a multi-line comment begins with a slash and an asterisk (/*) and ends with an asterisk and slash (*/). Here’s an example of a multi-line comment. Example
JavaScript Getting Started
Getting Started with JavaScript Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge of HTML and CSS. If you’re just starting out in the world of web development, start learning from here » Well, let’s get started with the most popular client-side scripting language. Adding JavaScript to Your Web Pages There are typically three ways to add JavaScript to a web page: The following sections will describe each of these procedures in detail: Embedding the JavaScript Code You can embed the JavaScript code directly within your web pages by placing it between the <script> and </script> tags. The <script> tag indicates the browser that the contained statements are to be interpreted as executable script and not HTML. Here’s an example: Example The JavaScript code in the above example will simply prints a text message on the web page. You will learn what each of these JavaScript statements means in upcoming chapters. Note: The type attribute for <script> tag (i.e. <script type=”text/javascript”>) is no longer required since HTML5. JavaScript is the default scripting language for HTML5. Calling an External JavaScript File You can also place your JavaScript code into a separate file with a .js extension, and then call that file in your document through the src attribute of the <script> tag, like this: <script src=”js/hello.js”></script> This is useful if you want the same scripts available to multiple documents. It saves you from repeating the same task over and over again, and makes your website much easier to maintain. Well, let’s create a JavaScript file named “hello.js” and place the following code in it: Example Now, you can call this external JavaScript file within a web page using the <script> tag, like this: Example Note: Usually when an external JavaScript file is downloaded for first time, it is stored in the browser’s cache (just like images and style sheets), so it won’t need to be downloaded multiple times from the web server that makes the web pages load more quickly. Placing the JavaScript Code Inline You can also place JavaScript code inline by inserting it directly inside the HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress, onload, etc. However, you should avoid placing large amount of JavaScript code inline as it clutters up your HTML with JavaScript and makes your JavaScript code difficult to maintain. Here’s an example: Example The above example will show you an alert message on click of the button element. Tip: You should always keep the content and structure of your web page (i.e. HTML) separate out from presentation (CSS), and behavior (JavaScript). Positioning of Script inside HTML Document The <script> element can be placed in the <head>, or <body> section of an HTML document. But ideally, scripts should be placed at the end of the body section, just before the closing </body> tag, it will make your web pages load faster, since it prevents obstruction of initial page rendering. Each <script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code, so placing them in the head section (i.e. <head> element) of the document without any valid reason will significantly impact your website performance. Tip: You can place any number of <script> element in a single document. However, they are processed in the order in which they appear in the document, from top to bottom. Difference Between Client-side and Server-side Scripting Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by the web browser, while server-side scripting languages such as PHP, ASP, Java, Python, Ruby, etc. runs on the web server and the output sent back to the web browser in HTML format. Client-side scripting has many advantages over traditional server-side scripting approach. For example, you can use JavaScript to check if the user has entered invalid data in form fields and show notifications for input errors accordingly in real-time before submitting the form to the web-server for final data validation and further processing in order to prevent unnecessary network bandwidth usages and the exploitation of server system resources. Also, response from a server-side script is slower as compared to a client-side script, because server-side scripts are processed on the remote computer not on the user’s local computer. You can learn more about server-side scripting in PHP tutorial section.
JavaScript Tutorial
JavaScript is the most popular and widely used client-side scripting language. Client-side scripting refers to scripts that run within your web browser. JavaScript is designed to add interactivity and dynamic effects to the web pages by manipulating the content returned from a web server. JavaScript was originally developed as LiveScript by Netscape in the mid 1990s. It was later renamed to JavaScript in 1995, and became an ECMA standard in 1997. Now JavaScript is the standard client-side scripting language for web-based applications, and it is supported by virtually all web browsers available today, such as Google Chrome, Mozilla Firefox, Apple Safari, etc. JavaScript is an object-oriented language, and it also has some similarities in syntax to Java programming language. But, JavaScript is not related to Java in any way. JavaScript is officially maintained by ECMA (European Computer Manufacturers Association) as ECMAScript. ECMAScript 6 (or ES6) is the latest major version of the ECMAScript standard. Tip: Our JavaScript tutorial will help you to learn the fundamentals of JavaScript scripting language, from the basic to advanced topics step-by-step. If you’re a beginner, start with the basics and gradually move forward by learning a little bit every day. What You Can Do with JavaScript There are lot more things you can do with JavaScript. The list does not end here, there are many other interesting things that you can do with JavaScript. You will learn about all of them in detail in upcoming chapters. What This Tutorial Covers This JavaScript tutorial series covers all the fundamental programming concepts, including data types, operators, creating and using variables, generating outputs, structuring your code to make decisions in your programs or to loop over the same block of code multiple times, creating and manipulating strings and arrays, defining and calling functions, and so on. Once you’re comfortable with the basics, you’ll move on to next level that explains the idea of objects, the Document Object Model (DOM) and Browser Object Model (BOM), as well as how to make use of the native JavaScript objects like Date, Math, etc., and perform type conversions. Finally, you’ll explore some advanced concepts like event listeners, event propagation, borrowing methods from other objects, hoisting behavior of JavaScript, encoding and decoding JSON data, as well as detailed overview of new features introduced in ECMAScript 6 (or ES6).
Tabs and Pills
Bootstrap Nav Components Bootstrap provides an easy and quick way to create basic navigation as well as components like tabs and pills which are very flexible and elegant. All the Bootstrap’s nav components, including tabs and pills, share the same base markup and styles through the base .nav class. Creating Basic Nav with Bootstrap You can use the Bootstrap .nav class to create a basic navigation menu, like this: Example — The output of the above example will look something like this: Note: You can use the class .disabled to make a link look like disabled. But, the .disabled class only changes the visual appearance of the link by making it gray and removing the hover effect, however the link will remain clickable unless you remove the “href” attribute. Alignment of Nav Items By default, navs are left-aligned, but you can easily align them to center or right using flexbox utilities. The following example uses the class .justify-content-center to align nav items to center. Example — The output of the above example will look something like this: Similarly, you can align nav items to right using the class .justify-content-end, like this: Example — The output of the above example will look something like this: Moreover, you can even vertically stack your nav items by changing the flex item direction with the class .flex-column. Also, if you want to stack your nav vertically on smaller viewports but not on others, use it with responsive breakpoint (e.g., .flex-sm-column). Example — The output of the above example will look something like this: Creating the Basic Tabs Simply, add the class .nav-tabs to the basic nav to generate a tabbed navigation, like this: Example — The output of the above example will look something like this: See the tutorial on Bootstrap tabs to learn how to create dynamic tab to toggle between content. You can also add icons to your tab items to make it more attractive, as shown here: Example — The output of the above example will look something like this: See the tutorial on Bootstrap icons to learn how to use icons in Bootstrap. Also, check out Bootstrap icons classes to explore the icons provided by Bootstrap. Creating the Pills Nav Similarly, you can create pill based navigation by adding the class .nav-pills on the basic nav instead of class .nav-tabs, as shown in the following example: Example — The output of the above example will look something like this: Similarly, like nav tabs you can also add icons to your pills nav to make it more attractive: Example — The output of the above example will look something like this: Additionally, you can apply the class .flex-column on the .nav element to make the pills nav appear vertically stacked. You can alternatively use responsive versions (e.g., .flex-sm-column) if you need to stack them on specific viewports but not on others. Example — The output of the above example will look something like this: Bootstrap Nav with Dropdown Menus You can add dropdown menus to a link inside tabs and pills nav with a little extra markup. The four CSS classes .dropdown, .dropdown-toggle, .dropdown-menu and .dropdown-item are required in addition to the .nav, .nav-tabs or .nav-pills classes to create a simple dropdown menu inside tabs and pills nav without using any JavaScript code. Creating Tabs with Dropdowns The following example will show you how to add simple dropdown menu to a tab. Example — The output of the above example will look something like this: Creating Pills with Dropdowns The following example will show you how to add simple dropdown menu to a pill nav. Example — The output of the above example will look something like this: You will learn more about dropdown menus later in Bootstrap dropdowns chapter. Fill and Justify Nav Component You can force your .nav-items to extend and proportionately fill all available width using the class .nav-fill on the .nav element. In the following example all horizontal space is occupied by the nav items, but every nav item doesn’t have the same width. Example — The output of the above example will look something like this: Alternatively, you can use the class .nav-justified instead of.nav-fill, if you want nav that fills all horizontal space as well as every nav item has the same width. Example — The output of the above example will look something like this:
Bootstrap Icons
Using Icons in Bootstrap 5 Bootstrap now includes over 1,300 high quality icons, which are available in SVGs, SVG sprite, or web fonts format. You can use them with or without Bootstrap in any project. The advantage of using font icons is, you can create icons of any color just through applying the CSS color property. Also, to change the size of icons you can simply use the CSS font-size property. Now, let’s see how to include and use Bootstrap icons on a web page. Including Bootstrap Icons in a Web Page The simplest way to include Bootstrap icons in a web page is using the CDN link. This CDN link basically points to a remote CSS file that includes all the necessary classes to generate font icons. You can include Bootstrap icons in a Bootstrap template as well as in a simple web page without using the Bootstrap framework. Let’s take a look at the following example: Example How to Use Bootstrap Icons in Your Code To use Bootstrap icons in your code you’ll require an <i> tag with an individual icon class .bi-* applied on it. The general syntax for using Bootstrap icons is: <i class=”bi-class-name“></i> Where class-name is the name of the particular icon class, e.g. search, person, calendar, star, globe, facebook, twitter, and so on. See the list of all Bootstrap icons classes. For example, to place search icon inside a button you could do something like this: Example — The output of the above example will look something like this: Similarly, you can place icons inside the navs, forms, tables, paragraphs or anywhere you want. In the next chapter you will see how to use these icons in Bootstrap nav components. Note: Remember to leave a space after the closing tag of icon element (i.e. after </i> tag), when using the icons along with the strings of text such as inside buttons or navigation links, to ensure that there is proper spacing between the icon and text. Using Font Awesome Icons in Bootstrap You can also use external icon libraries in Bootstrap. One of the most popular and highly compatible external icon library for Bootstrap is Font Awesome. It provides over 675 icons which are available in SVG, PNG, as well as in web font format for better usability and scalability. You can simply use the freely available font-awesome CDN link to include it in your project. Let’s take a look at the following example to understand how it basically works: Example How to Use Font Awesome Icons in Your Code To use Font Awesome icons in your code you’ll require an <i> tag along with a base class .fa and an individual icon class .fa-*. The general syntax for using font-awesome icons is: <i class=”fa fa-class-name“></i> Where class-name is the name of the particular icon class, e.g. search, user, calendar, star, globe, facebook, twitter, and so on. See the list of all Font Awesome icons classes. For example, you can place font-awesome search icon inside a button like this: Example — The output of the above example will look something like this: Similarly, you can place Font Awesome icons inside the navs, forms, tables, paragraphs, and other components in the same way as you do with Bootstrap icons.
Bootstrap Media Objects
Using the Media Object in Bootstrap Bootstrap media object has been discontinued from version 5. However, you can still create a layout that contains left- or right-aligned media object like images or video alongside the textual content such as blog comments, Tweets, etc. using the flex and spacing utility classes. Example — The output of the above example will look something like this: You can also create other variations of media object. Apply the image modifier classes like .rounded or .rounded-circle to the image to create rounded corner or circular image. Example — The output of the above example will look something like this: Creating Nested Media Objects Media objects can also be nested inside other media object. It can be very useful for creating comment threads in a blog post. Let’s check out an example: Example — The output of the above example will look something like this: Alignment of Media Objects You can also change the horizontal alignment of content and media by simply tweaking the HTML code itself, as demonstrated in the following example: Example — The output of the above example will look something like this: Besides that you can also align the images or other media at the middle or bottom of the content block using the flexbox utilities classes, for example, you can use the class .align-self-center for vertical center alignment, and the class .align-self-end for bottom alignment. By default, the media inside a media object is top aligned. Here’s an example: Example
Bootstrap Cards
Using the Bootstrap Cards Bootstrap card is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options. Card replaces panel, well, and thumbnail components in old Bootstrap 3 version. In the following sections, you will see what you can do with the card component. Creating a Basic Card The card markup is pretty straight forward. The outer wrapper require the base class .card, whereas content can be placed inside the .card-body element. The following example will show you how to create a card with a picture, mixed with some text content and a button. Example — The output of the above example will look something like this: Note: Card doesn’t have fixed width, they’ll occupy the full width of its parent element. So, if you need a fixed width card you need to apply the width property on card yourself. Also, card have no margin by default, use spacing utility classes if needed. Content Types for Card Component The card component support a wide variety of content, including images, text, list groups, links, navs, and more. Here are the examples of what’s supported by the card. Body Only Card You can simply use .card with .card-body within, whenever you need to create a padded box. Example — The output of the above example will look something like this: Card with Titles, Text, and Links Further, you can also place title and links inside the card along with text, like this: Example — The output of the above example will look something like this: Card with Header and Footer You can also add header and footer within your cards using the .card-header and .card-footer class, respectively. Let’s take a look at the following example: Example — The output of the above example will look something like this: Tip: You can use text align utility classes such as .text-center and .text-end to align card’s content to the center and right end, respectively. By default they’re left aligned. Placing List Groups within Card You can also place list groups inside the card along with other content types, as shown here. Example — The output of the above example will look something like this: Mix and Match Multiple Content Types within Card Feel free to mix and match multiple content types to create the card you need. The following example will create a fixed-width card with an image, text, list group, and hyperlinks. Example — The output of the above example will look something like this: Adding Navigation to Cards You can also add Bootstrap’s nav components such as tabs and pills to the card header. To add tabs navigation to a card simply place the tabs markup inside the card header, and the tabs content inside the card body. You are also required to use an additional class .card-header-tabs on the .nav element along with the class .nav-tabs for proper alignment. Let’s try out the following example which creates an elegant tabbed navigation. Example — The output of the above example will look something like this: Similarly, you can add pills nav to the card by using an additional class .card-header-pills along with the class .nav-pills on the .nav element, as shown below: Example — The output of the above example will look something like this: Customizing the Card Styles There are several options available for customizing the card’s backgrounds, borders, and color. Customizing Background and Color You can simply use the background and color utility classes to change the appearance of a card. Let’s try out the following example to understand how it basically works: Example — The output of the above example will look something like this: Customizing Border and Color Similarly, you can customize the border and text color of any card using the text and border utility classes. Just apply these classes on the .card or its child elements, as shown below: Example — The output of the above example will look something like this: Card Layout Options In addition to styling of the cards, Bootstrap also includes a few options for laying out the series of cards. However, these layouts are not responsive yet. Creating the Card Groups You can use card groups to render cards as a single, attached element with equal width and height columns. However, cards inside a card group become horizontally stacked on extra small devices (i.e. viewport width <576px). Let’s try out an example and see how it actually works: Example — The output of the above example will look something like this: Creating the Card Grids You can use the Bootstrap grid system and its .row-cols-* classes to control how many grid columns (wrapped around your cards) to show per row. For example, you can use the class .row-cols-1 to show one card per row, similarly you can use the class .row-cols-md-2 to show two cards per row, from the medium breakpoint up (i.e. viewport width ≥768px). Example — The output of the above example will look something like this: Creating Horizontal Cards You can also create horizontal cards where image and text content are placed side-by-side using a combination of grid and utility classes, as shown in the following example: Example — The output of the above example will look something like this: Card Image Overlays You can even turn an image into a card background and place the card’s text on the top it using the class .card-img-overlay in place of .card-body. Depending on the image, you may need additional styles for better adjustments. Let’s check out an example: Example — The output of the above example will look something like this: Note: The card content should not be larger than the height of the image. If content is larger than the image the content will be displayed outside the image. Text Alignment inside Card You can easily change the text alignment of any card—entirely or specific parts—with the text alignment utility classes. For example, you can use the class .text-center and .text-end to align the card’s text content to the center and to the right end, respectively. Example — The output of the above example will look something like this: Specifying Card Size Cards have no specific width, they are 100% wide by default. However, you can
Bootstrap Images
Styling Images with Bootstrap Images are very common in modern web design. So styling images and placing it properly on the web pages is very important for improving the user experience. Using the Bootstrap built-in classes you can easily style images such as making the round cornered or circular images, or give them effect like thumbnails. Example — The output of the above example will look something like this: Creating Responsive Images and Videos With Bootstrap you can make the images responsive too. Just add the class .img-fluid to the <img> tag. This class mainly applies the styles max-width: 100%; and height: auto; to the image so that it scales nicely to fit the containing element — in case if the width of the image is larger than the containing element itself. Check out the following example to see how it works: Example Note: When making the responsive layouts consider making your images responsive too, otherwise if an image width is larger than the parent element’s width in any case, it will overflow and may break your web page layout. You can also make the video or slideshow embedded in a web page responsive without affecting its original aspect ratio. To do this wrap any embed like an <iframe>, or <video> in a <div> element and apply the class .embed-responsive, and an aspect ratio class such as .embed-responsive-16by9. You can optionally apply an explicit descendant class .embed-responsive-item on the embedded element to match the styling for other attributes. Here’s is an example: Example In the above example, we’ve created the 4 responsive embedded videos with 4 different aspect ratios (21:9, 16:9, 4:3, and 1:1) by using the classes .ratio-21×9, .ratio-16×9, .ratio-4×3, and .ratio-1×1, respectively in addition to the base class .ratio on the wrapper element. Tip: The aspect ratio of an image describes the proportional relationship between its width and its height. Two common videographic aspect ratios are 16:9 and 4:3. Horizontal Alignment of Images You can use the text alignment classes such as .text-center, and .text-end on the parent container to align the inline images horizontally center and right. You can also align images to the left and right within a larger box using the classes .float-start and .float-end. However, to center align the block-level images you need to use the .mx-auto margin utility class. Let’s try out the following example to understand how it really works: Example
Bootstrap Button Groups
Creating Button Groups with Bootstrap In the previous chapter you’ve learnt how to create different types of individual buttons and modify them with predefined classes. Bootstrap however, also allows you to group a series of buttons together in a single line through the button group component. To create a button group just wrap a series of buttons with .btn class in a <div> element and apply the class .btn-group on it. You can additionally apply the class .active on an individual button to indicate the active state. Let’s take a look at the following example: Example — The output of the above example will look something like this: Similarly, you can also create button groups using outline buttons, like this: Example — The output of the above example will look something like this: See the tutorial on Bootstrap stateful buttons to learn how to enable radio buttons and checkboxes like toggling on button groups without using any JavaScript code. Mixed Styles Button Groups You can also mix and match different button styles to create button groups like this: Example — The output of the above example will look something like this: Creating Button Toolbar You can also combine sets of button groups together for creating more complex components like button toolbar. To create button toolbar just wrap sets of button groups in a <div> element and apply the class .btn-toolbar on it, as shown in the following example: Example — The output of the above example will look something like this: Height Sizing of Button Groups Instead of applying button sizing classes to each button in a group, you can simply apply button group sizing classes like .btn-group-lg or .btn-group-sm directly to each .btn-group element to create larger or smaller button groups, as shown in the example below: Example — The output of the above example will look something like this: Nesting Button Groups Button groups can also be nested. The following example demonstrates how to place a .btn-group within another .btn-group to create dropdown menus inside button groups. Example — The output of the above example will look something like this: You will learn about Bootstrap dropdowns in detail in the advanced section. Vertically Stacked Button Groups You can also make the button groups appear vertically stacked rather than horizontally. To do this just replace the class .btn-group with the class .btn-group-vertical, like this: Example — The output of the above example will look something like this: Creating Justified Button Groups You can also stretch your button groups to fill all the available width by applying the flex utility class .d-flex to the .btn-group element. Every button has equal width in this case. Example
Bootstrap Buttons
Creating Buttons with Bootstrap Buttons are the integral part of a website and application. They are used for various purposes like, submit or reset an HTML form, performing interactive actions such as showing or hiding something on a web page on click of the button, redirecting user to another page, and so on. Bootstrap provides a quick and easy way to create and customize the buttons. Bootstrap Button Styles Different classes are available in Bootstrap for styling the buttons as well as to indicate the different states or semantic. Button styles can be applied to any element. However, it is applied normally to the <a>, <input>, and <button> elements for the best rendering. The following example will show you how to create different styles of buttons in Bootstrap: Example — The output of the above example will look something like this: Bootstrap Outline Buttons You can also create outline buttons by replacing the button modifier classes, like this: Example — The output of the above example will look something like this: Changing the Sizes of Buttons Bootstrap gives you option further to scaling a button up or down. To make buttons larger add an extra class .btn-lg to the buttons, like this: Example — The output of the above example will look something like this: Similarly, to make buttons smaller add an extra class .btn-sm to the buttons, like this: Example — The output of the above example will look something like this: You can also create full-width or block buttons (buttons that covers the full width of the parent elements) through using the Bootstrap’s display and gap utility classes. These utilities offers much greater control over spacing, alignment, and responsive behaviors. Example — The output of the above example will look something like this: You can also create responsive variation of these buttons using the .d-{breakpoint}-block classes. In the following example buttons will be vertically stacked on small and extra small devices (i.e. viewport width <768px). From medium (md) breakpoint up .d-md-block replaces the .d-grid class, thus nullifying the .gap-2 class. Let’s try it out and see how it really works: Example Bootstrap Disabled Buttons Sometimes we need to disable a button for certain reasons, for example, a user in case is not eligible to perform this particular action, or we want to ensure that user should performed all other required actions before proceed to this particular action. Let’s see how to do that. Creating Disabled Buttons Using Button and Input Element Buttons created through <button> or <input> tag can be disabled by adding the disabled attribute to the respective element, as shown in the following example: Example — The output of the above example will look something like this: Creating Disabled Buttons Using Anchor Elements Buttons created through <a> tag can be disabled by adding the class .disabled, like this: Example — The output of the above example will look something like this: Note: The .disabled class only make links visually appear like disabled, however the link will remain clickable unless you remove the href attribute from it. Alternatively, you could implement custom JavaScript to prevent those clicks. Bootstrap Active Buttons Moreover, you can also apply the class .active to force the buttons look like active (i.e. pressed). Usually you don’t need to add this class to the buttons, as their active state is automatically styled by the Bootstrap using CSS :active pseudo-class. Here’s an example: Example — The output of the above example will look something like this: Creating Spinner Buttons With Bootstrap you can easily include spinner icon in a button to indicate the loading state in your application. Check out the following example to see how it works: Example — The output of the above example will look something like this: In the next chapter you will learn how to combine multiple buttons horizontally or vertically in a line like toolbars using the Bootstrap button groups component. Also, in the advanced section you will learn how to create toggle buttons without using any JavaScript code.