Learning HTML From Scratch – Part 2 – Attributes, Links and Images

In part 1 of this series, I started the basics of what HTML is and how html tags work. In this second part, I will go into more detail to show how to use tags with attributes on them to make links and include images in your html pages.

What is an attribute?

HTML tags can have attributes on them, which are simply named values that add additional details to the tag. An attribute on an html tag can specify a page to link to, an image to display, the placeholder text in a textbox, etc. They are included as part of the tag using the attribute name and value, as shown below:

[html light=”true”]
[raw]
<img alt="Blue Honda Accord" src="newcar.jpg">
<a href="http://www.microsoft.com">Microsoft</a>
[/raw]
[/html]

You have the name of the attribute, an equal sign, then the value in single or double quotes. If there is more than one attribute, they are separated with a space.

In the examples above, alt and src are attributes of the <img> tag, and href is an attribute of the <a> tag. Tags share some attribute names in common, but each tag often has some attributes that are specific to that tag. The individual attributes will be explained in more detail below.

Like the tag itself, the attribute names are not case sensitive, and they can appear in any order on the tag. The same attribute cannot be duplicated on the same tag.

Creating Links

While you would think the obvious tag to create a link would be the link tag, the tag used for links is actually the <a> tag. There is a <link> tag, but it serves a completely different purpose (it is used to include an external style sheet into a page).

Instead the <a> tag (for anchor) is used to create links to pages within your site, to external sites, and to places within the current page or another page.

The <a> tag’s main attribute is called href (which stands for hypertext reference). You use href to define the page or site that you are linking to. You put the label for the link (what the link says on the page) in between the opening and closing a tags. Here are some examples – note that all of these would go inside the <body> tag in your page:

[html]
[raw]
<a href="http://www.google.com">Google</a>
<a href="page2.html">Next page</a>
<a href="#top">Return to top</a>
[/raw]
[/html]

The first example links to Google.com. Since this is a link to an external site, you need to include the full URL including the http:// or https:// – you can’t just put www.google.com. Any time you link to something outside of the site your page is on, you have to use the full URL. Note: you can always use a full URL even for pages within your own site.

The second example links to another page in the same site with a name of page2.html. This is known as a relative path or link, which is explained in more detail here. Again, you can also use the full URL to the page instead (ie.. http://www.mysite.com/page2.html).

Finally, the third example links to a place in the current page called “top”. The # sign in front of the name indicates that it is a link to a place within the document. For more information on how to define places within a page to link to, see this.

Note: there is an attribute you can use to indicate that a link should open a new page instead of replacing the existing one. It is the target attribute. You use the “_blank” value to specify that a link opens up a new tab or window. For more information on target, see this.

Here is a sample page with some different links in it. It includes a tag you’ve not seen yet, which is  <br>.  It is used to put in a line break since HTML ignores line breaks in your html file. One of the links also uses target=”_blank” to open in a new window.

Note: <br> It is one of the few HTML tags that does not have a closing tag. It is used by itself to indicate a line break. You will sometimes see <br/> (which is a combined opening and closing tag), but <br> is perfectly valid and most common.

Adding Images

To add an image to a web page, you use the <img> tag. Like <br>, the <img> tag has no closing tag. Its main attributes are src (source), which specifies the name and location of the image, and alt (alternative) which provides alternate descriptive text for the picture that is important for accessibility purposes and as a placeholder while the image loads or if it fails to load).

Don’t confuse alt text with a caption – the alt text is not usually displayed. Unless the image is simply decorative, you should always provide alt text describing the meaning of the image.

Examples:

[html][raw]
<img src="http://www.commonchaos.com/wp-content/uploads/2011/07/happy-cat.jpg" alt="Happy cat picture">
<img src="cat.jpg" alt="another cat picture">
[/raw]
[/html]

Like links using the <a> tag, if the image is not on the current website, you must use the full URL to the image to include it, including the http:// or https://. This is shown in example # 1 above. It uses the full URL to the image on an external site.

In example number 2, only the file name was specified. The browser would look for the image in the same folder as the web page referencing it. The same rules about relative paths with links applies to images. More details on using relative paths can be found here. It’s simply a way to refer to a file that is in a different location on your site than the current page.

You can also combine a link and an image so that a link is opened when you click on an image. This is often used to show a smaller picture on a page, and link to a more detailed version. To do this, you simply put the <img> tag in between the opening and closing <a> tag with the link specified on it. Example:

[html light=”true”]
[raw]
<a href="largepicture.jpg"><img src="smallpicture.jpg" alt="Sunset at the beach"></a>
[/raw][/html]

I’ve created a sample page that shows this in action. It has a picture from an external site, a local image, and an image that is linked to another image. You can view the live sample here

The sample page uses the <h3> tag, which will be explained in an upcoming post on text formatting. It’s a heading tag that indicates the text in between is a heading. As a reminder, you can right click on the sample page in your browser and select View Source to see the HTML I used to create the page.

Summary

In this post, you built on what you learned in the first post about html tags and their use. You learned that attributes are settings on an HTML tag that give details like what picture to show, what page to link to, etc. You learned that the <a> tag, along with its href attribute, is used to create links to other pages, sites, and sections of pages. Finally, you learned how to show an image in a web page using the <img> tag along with its src attribute to specify the image to use and the alt attribute to label it. Combining both techniques, you also learned to add a link to an image.

As an exercise, try creating a page to display some of your favorite pictures. You can either use the full URL to them online, or save them locally and put them in the same folder with your html file and use their file name. Link one of the pictures to a site or a larger version of the same image.

Also try creating a list of your favorite web page links. Add a link for each site and give it a name (put the link text between the opening and closing <a> tags). Use <br> to separate each line. You can also try creating a second page in the same folder and linking to it using the file name of the new file you create (ie..page2.html).

In the next part we will cover some of the tags that help to format your text and give your page structure, such as headers, footers, etc.

Resources:

Attribute Reference (list of attributes for each HTML tag)
What are relative paths/links? (understanding how to use a relative link to a page or image)
W3 Attribute Specification (explains attributes and when to use single or double quotes)
Target Attribute of the Anchor Tag (explains the values of target on a link)
Alternative Text (understanding the importance of the ALT attribute for accessibility)
.

Learning HTML From Scratch – Part 1

Whether you want to be a programmer, a web designer, mobile app developer or get some other tech related job, having a strong knowledge of HTML is extremely helpful. Nearly all tech touches the Internet in some way, and HTML is the backbone of the entire web. Learning how to read and write HTML, even if you ultimately won’t work with it by hand , will provide a strong foundation.

At its most basic, HTML is just a specially formatted text file that describes how to display a web page. You can use simple text editors like Notepad or more sophisticated development tools like Visual Studio, Adobe Dreamweaver, Brackets, etc… to easily create and edit HTML files. I’ve included some links to some common editors at the end of the post. I’ve also included a link to an HTML playground page that allows you to edit HTML and preview the results in real time right in your browser.

It’s all about tags

Everything in HTML is made up of a tag. These are small pieces of text surrounded by brackets that describe to the web browser something about the document or what to display on the page.

Every HTML document (page) starts with the HTML tag, which looks like this:
<HTML> or <html> (tag case doesn’t matter).

Most (but not all) HTML tags have a closing tag that signifies when the tag ends. A closing tag is the same as the opening tag, but has a forward slash (/) after the first bracket, before the tag name. Just as the <html> tag starts a document, the </html> tag closes it. Not every tag has a closing tag, but most do. I’ll explain the tags that don’t have a closing tag in the future – but most that you will use do.

Some additional examples of tags (which I will define later): <strong>, <p>, <a>, <div>, <script>, <img>

I’ve included a link below in the resources to a full list of HTML tags for reference. I won’t be covering every one but they all work in a similar way.

HTML Is Hierarchical

An HTML document is processed from top to bottom. Tags are put between other opening and closing tags to create the structure of the page. Tags act as containers for other tags.

Every HTML page has two sections inside of the html tag. The first is the <head> section, and the second is the <body>. Note that blank spacing and line feeds are for readability – they are not necessary and are ignored by the browser.

Example:

[html light=”true”][raw]
<html>

<head>

</head>

<body>

</body>

</html>

[/raw][/html]

Notice that <head> and <body> are both inside of the <html></html> tags. Additional tags go inside of the <head> and <body> tags to create the page.

The HEAD Tag

The <head> tag represents the header of the document. Don’t confuse it with the header at the top of a page that contains menus and navigation. This section is not displayed on the page itself – it contains information about the document, such as the title, search engine keywords, character set, linked external files, etc..

The most common tag inside of <head> is the <title> tag. Whatever you put between <title></title> is what is shown in the title bar or tab in a web browser, and is also used by search engines. Example:

[html light=”true”]
[raw]
<head>
<title>Learning HTML From Scratch</title>
</head>
[/raw]
[/html]

That will set the page title to Learning HTML From Scratch. Notice that <title></title> surrounds the title, and that the title tag is inside of the <head> tag.

The BODY Tag

Unlike the <head> section, <body> is what is actually displayed in the browser. Whatever is inside of the <body> section is what is shown as the page itself in the browser. It is where the bulk of your tags will go. The contents of body are processed from top to bottom. Here is a sample:

[html light=”true”]
[raw]
<html>
<head>
<title>Sample html page</title>
</head>
<body>
<strong>Hello World!</strong>
</body>

</html>[/raw]
[/html]

This will show Hello World! in bold in the browser. The example contains one other tag – strong, which will be explained in more detail later. The strong tag makes text bold (you will also encounter pages that use the b tag, which does the same thing but has been deprecated in favor of the strong tag and using css styling for bold).

This is a web page at its most basic, but this is the basis for every web page. You can view the sample above as a web page here.

Summary of Part 1

An HTML page is just specially formatted text that a browser reads to display a web page. It uses tags to define the structure and details of the web page. A tag often has a corresponding closing tag which indicates where that tag ends. Every HTML page starts and ends with the <html> tag. Inside of the <html> tag, there are two sections – <head> and <body>. The head section contains information about the page, and the body section is the actual content of the page that gets displayed.

To experiment on your own, use a text editor and create a new file. Put in the html, head and body tags. In the head section, put a title between two title tags. In the body, put in some text and make some of it (or all of it) bold by surrounding it with the strong tag. Save the file with an .html or .htm extension, and then open the file in a web browser to see the results. Just go to the folder where you saved the html file and right click on it and select Open – it should open in your default web browser. You can right click on the page in your browser and select View Source to view the HTML.

In the next part, I’ll explain html tag attributes to create links, display images, and more.

Resources:

Notepad++ (Free text editor with HTML highlighting)
Brackets (Free code editor)
Visual Studio Code (Free code editor)
A list of all HTML tags (for reference)
Lightweave HTML Playground (for experimenting with HTML in your browser in real time)

Creating A Simple DisplayFor Template In ASP.NET MVC

When building web applications, the DisplayFor and EditorFor HTML helpers are extremely useful to quickly build pages from your model. However, sometimes you would like a bit more control over their display.

For example, by default, boolean fields show as a disabled dropdown with the value selected. I would prefer to simply output the value – true or false – as plain text.

In order to replace the template used, first create a folder inside of the Shared folder under Views called DisplayTemplates.

Then create a partial view file matching the name of the data type, in this case Boolean.cshtml

Solution explorer with DisplayTemplate

Inside the Boolean.cshtml file, add the following code:

[csharp]
@model Boolean?

@(Model.HasValue? Model.Value.ToString() : "")
[/csharp]

That’s all you need to do. Any views that use DisplayFor on a boolean will pick up the new format automatically.

You can do a lot more than what is shown here. This is a pretty good guide to creating simple and advanced EditorFor templates. The same concepts apply for DisplayFor, just a different folder (DisplayTemplates vs EditorTemplates):

Extending Editor Templates for ASP.NET MVC

 

Customize Title Bar Colors In Windows 10 WinJS Apps

In my previous post, I showed how to set the title bar color in Windows 10 C#/XAML apps. It’s easy to do the same thing in a Windows 10 Javascript app as well, the syntax is slightly different. I added this code to the main js file for the app (example: default.js), right before the app.Start() method call.

[javascript]
var titleBar = Windows.UI.ViewManagement.ApplicationView.getForCurrentView().titleBar;
titleBar.backgroundColor = Windows.UI.Colors.blue;
titleBar.buttonBackgroundColor = Windows.UI.Colors.blue;
titleBar.foregroundColor = Windows.UI.Colors.white;
titleBar.buttonForegroundColor = Windows.UI.Colors.white;
[/javascript]

That’s all it takes.

Customize Title Bar Colors In Windows 10 XAML Apps

Windows 10 apps can have customized title bar colors (for example, the Mail and Calendar apps) instead of the default white (or accent color in an upcoming Windows 10 update). Changing the title bar color in a Windows 10 XAML app is easy. In the constructor for your main XAML file (ie..MainPage.xaml.cs), you get a reference to the title bar from the ApplicationView object’s GetForCurrentView() method. You can then set the colors of both the title bar and the window controls by setting the properties:

[csharp]
public MainPage()
{
this.InitializeComponent();
var t = ApplicationView.GetForCurrentView().TitleBar;
t.BackgroundColor = Colors.Indigo;
t.ForegroundColor = Colors.White;
t.ButtonBackgroundColor = Colors.Indigo;
t.ButtonForegroundColor = Colors.White;

}
[/csharp]

That’s all it takes. You could easily implement user customizeable title bar colors for your app as well.

Using Extension Methods in a ASP.NET MVC Razor View

,

Extension methods were added in C# 3.0 and are a great way to add commonly used functionality to your projects in an object oriented way that cuts down on repetitive code. While extension methods are an underlying feature of C#, I am going to focus on their use in a view in an ASP.NET MVC project. The same principles apply to using them in any C# code..

I write a lot of ecommerce-related web applications, so I am constantly having to output prices formatted as currency. While I could just use the String.format method directly in a view, I prefer something a little more elegant and less repetitive. By adding a ToCurrency method to the decimal type, I can easily output a formatted string.

Start by adding a new class to your project with its own namespace, for example myproject.Extensions:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{

 

Add a static class – this class will have methods added to it that will become your extension methods:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{
    public static class Extensions
    {
    
    }
}

Each static method you add to the class will become an extension method. You tie it to a particular type by using the this keyword and a parameter of the type you want to extend:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myProject.Extensions
{
    public static class Extensions
    {
        public static string ToCurrency(this decimal amount)
        {

            return String.Format("{0:C}", amount);

        }
    }
}

The ToCurrency method will be added to the decimal type because it is specified as the parameter type and includes the keyword this. I am simply passing the parameter to the String.Format method and returning a formatted string.

Calling the extension method either in other code such as a controller or within a view is simple. You just need to be certain to include the namespace in your class or view with a using statement. This is an example of it in a Razor view:

 

@model myProject.Models.Product
@using myProject.Extensions;

<span>@Model.Price.ToCurrency()</span>

The price property of the Product class is a decimal, so the method is available as if it were part of the underlying type.

You can add extension methods to any class the same way. Another example is providing a formatted address for an address object:

public static string GetFormatted(this Address address)
{
 string a=address.Name+"<br>";

if(address.Company!=null)
{
a+=address.Company+"<br>";
}
a+=address.Address1+"<br>";
if(address.Address2!=null)
{
a+=address.Address2+"<br>";
}
a+=address.City+", "+address.State+" "+address.Zip
return a;

}

Then, within a view, you can easily output a formatted address without having to put all the logic into the view:

@Model myProject.Models.Order
@using myProject.Extensions

<div>
@Model.BillingAddress.GetFormatted()
</div>

Since the BillingAddress property of the Order object is of type Address, the extension method is available as if it were a native part of the class. While you could add the method directly to the underlying class, if you are working with Entity Framework or a class you may not have the source code to, you can extend it without having to modify the original class.

While you could just as easily create a library of functions to call, extension methods provide a more elegant solution to code reuse and providing utility functions. The can even be put into a separate class library project to reuse them between projects.

For more information about Extension methods, see:

http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx
http://csharp.net-tutorials.com/csharp-3.0/extension-methods/

Creating Simple Text Notifications in Windows 8 with C#

Windows 8 introduces a much improved notification system that allows your applications to notify users in a variety of ways, from local application notifications to push notifications and badges on live tiles.

The simplest type of notification is a toast notification, which is a message that appears temporarily in the corner of the users screen and then fades away. Various applications have used them for notification of events like users signing on or off, messages received, etc. Windows 8 supports them at the OS level, so you can provide consistent notifications in your applications.

The notification system is in the Windows.UI.Notifications namespace, so the first step is to include the namespace in your code:

using Windows.UI.Notifications;

The notification templates are XML documents, so you also need to include the Windows.Data.Xml.Dom namespace:

using Windows.Data.Xml.Dom;

Creating the notification is simple. First, you use the ToastNotificationManager to get a template to work with for your notification. The GetTemplateContent method returns an XML document containing the template of the type you pass to the method as a ToastTemplateType value. In this case, we just need a simple text template, so we will pass it ToastText01:

XmlDocument x = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

The Xml document that is returned looks like this:

<toast>
    <visual>
        <binding template="ToastText01">
            <text id="1"></text>
        </binding>  
    </visual>
</toast>

Pulling out the <text> element and appending a text node to it will set the text for the notification:

XmlNodeList toastTextElements = x.GetElementsByTagName("text");
toastTextElements[0].AppendChild(x.CreateTextNode("Copied to clipboard."));

Once the text is set, you create a ToastNotification object and pass the XML template to the constructor:

 ToastNotification toast = new ToastNotification(x);

Finally, you call the CreateToastNotifier method of the ToastNotificationManager and pass the ToastNotification object to the Show method to display it:

  ToastNotificationManager.CreateToastNotifier().Show(toast);

That’s all it takes. There are additional templates you can use that include spaces for images and formatted text. For more information on available templates, see http://msdn.microsoft.com/en-us/library/windows/apps/hh761494.aspx 

How to Center a DIV with CSS

I often find that sometimes the smallest things that were simple in regular HTML are frustratingly complex in CSS. Take, for example, centering a div. You can float it right, float it left, but there is no center. Using text-align: center does not center it either, it just makes any text inside of it centered.

It turns out it is very simple to do. The key is that you must specify a width for your div, either using an exact pixel width, a percentage, or some other measure like em units. Once you set the width, you just have to add left and right margins set to auto, and the div will be centered inside of the container it is in.

Continue reading “How to Center a DIV with CSS”

Tab Bar Controller Changes in Xcode 4

I am in the process of learning iOS development, and the tutorial I am using on the using tab bars was written for Xcode 3. In the tutorial, you add a third tab to the two that are created by default. It instructs you to use the attributes page for the tab bar controller to add another item:

 

Unfortunately, this option is gone in Xcode 4, and the method of adding a new tab is completely different. Here is a step by step demonstration of how to add a Tab Bar Item in Xcode 4.

Hopefully this will help someone who is confused by the change.

Using HTML5’s Data Attributes With jQuery

While the HTML5 specification apparently won’t be finalized until 2014, you can use one of its more useful new additions, the data attribute, right now with jQuery for easy access to extra data.

When you are creating a dynamic page, you often need to store some additional data on an html element that will be used later when interacting with the page. Right now, developers often use non-existent class names or the rel attribute as a solution, or they add their own attributes, which is not valid HTML.

For example:

<img src="picture.jpg" largeimage="picturelarge.jpg">


<li rel="menu1">Menu item</li>

Browsers just ignore attributes they don’t support, so it has no negative effect. While this works, it is not the most elegant solution and is not valid HTML.


HTML5 introduces the data attribute to html elements. You can add multiple data attributes to an element. It works differently than other html attributes. The attribute begins with data, then has a dash and the name of the data item.

Example:

<img id="pic" src="picture.jpg" data-large="picturelarge.jpg"

data-productid="52" data-license="creative commons">

The img tag has three data attributes – large, productid and license. These can be accessed by getting the attribute, or by using the element’s dataset object. Each data attribute becomes a named property of the dataset object:

 
el.dataset.productid

Unfortunately, that method is not useable right now because of lack of browser support for the dataset object.
 
The solution is to use jQuery 1.43 or later, which has full support for the data attributes through the data() method. It does not rely on the dataset object, so it is compatible with non-HTML5 browsers.
 
Using the img example above, you can access the values of the data attributes like this:

$('#pic').data('productid') // 52


$('#pic').data('large') // picturelarge.jpg

While you could have just used the attr() to retrieve the value using the full attribute name ("data-productid"), the data() method is more elegant and readable, and has enhanced functionality. It can handle json encoded attributes, for example:

<li id='line1' data-options='{"color":"black","interior":"gray"}'>


Aston Martin</li>

The options attribute is automatically parsed by the data() method into named properties:

$('#line1').data("options").color //black


$('#line1').data("options").interior //gray

Data can also be added through code to an element with the data() method. It also has an event model that can be attached to for processing when data is read or set. For more info on data(), see the jQuery documentation on it.

jQuery provides an excellent way to start using HTML5 now without having to wait until browsers catch up.