11 JavaScript/JQuery

If HTML is for content and CSS for presentation, than Javascript is for behavior. It really takes mastery of all three to become a web designer. It is, unfortunately, too much for this coures to tackle all three, so we merely touch on Javascript and give you some idea of how it works. If you want to learn more, try Kahn Academy or Codecademy for Javascript or Jquery.

Javascript goes as far back as the origin of the web. You will recall that the web was inspired by Apple’s Hypercard, which had been implemented in a proto-web kind of way in the offices where the web was born. Well, hypercard had a scripting language called Hyperscript that inspired Javascript.

Javascript transforms the content of web pages in much the same way as HyperScript transformed the content of the hypercard stacks. Javascript scripts are executed upon loading or by a user action, and do something to the content of the web page. Much of the added functionality on the web is due to Javascript.

Where Javascript Enters the Picture

When the browser requests content from the server, the document is fetched or constructed by server side scripting, crosses the HTTP divide, and arrives at the client (the browser). The browser then parses the content, starting with the header, and constructs the document, including the requests for additional resources such as the CSS stylesheet, JavaScript scripts, fonts, and images, and organizes all of it into the web page we are all familiar with. In the case of Ajax, additional material can be requested and received without flushing the existing page, allowing the page to be updated asynchronously.

The DOM

The browser processes, or parses the information, transforming the tags, attributes, content, etc., into nodes that form a tree according to the document object model, the DOM. See the demonstration.

HTML DOM tree

The browser attempts to heal any errors that come up as the document tree is constructed. Each browser does that in their own way, meaning that the tree structure of the document can be different from one browser to the next. Part of the HTML5 specification is to create a unified way for browsers to handle non-valid documents, making sure that all browsers create the same DOM for any given page.

JavaScript manipulates the properties and the elements in the DOM as soon as the page is loaded, or afterwards, if triggered by the user. Slight variations in how the different browsers handle JavaScript create big problems, which may or may not be the same from browser to browser. You can imagine that it used to be a real pain to program JavaScript.

This pain kept the more integrated Javascript implementations out of general usage, mostly relegating it to simple code snippets for much of its existence. The solution came with the development of cross browser JavaScript Libraries, which provide a simplified unified interface, or framework for implementing Javascript across the various browsers.

There are well over 50 of such open source libraries, of which jQuery is but one. They all simplify the task of creating highly responsive web pages, abstracting away browser specific features that let designers concentrate on design and user interactivity.

Then again, jQuery has won the hearts and minds of the web development community and has become ubiquitous since its release. It is the “write less, do more” library we all know and love.

The browsers have cleaned up their act and support a uniform DOM implementation, these days. While this alone does not make jQuery superfluous, it is possible to make the case to write Javascript instead of jQuery. If you wish to learn Javascript, you can read Eloquent Javascript (pdf) for free on the web.

jQuery

jQuery is one of the many JavaScript libraries created to ease JavaScript development. John Resig, the person who created the library, originally wanted to call it jSelect but the url was already taken, so it became jQuery. One of the most important things that jQuery does is provide a more uniform and easier to access ability to select DOM elements, removing the problems caused by different Javascript implementations and DOM error resolution.

jQuery is very flexible when it comes to selecting DOM elements with the jQuery function, and it works similar to the way selectors do in CSS.

In the same way that jQuery simplifies selecting DOM elements, it also makes manipulating the node objects much easier. It does not just return the DOM object but wraps each one of them with standard functions that make it really easy to manipulate them. You can show, toggle, hide, animate and otherwise manipulate and attach events to these objects with ease.

The Focus of jQuery

From a slideshow by John Resig:

In a nutshell:

  • $(“div”).addClass(“special”);
  • Find some elements — Better CSS Selector support than most browsers!
  • Now that we’ve found the elements, let’s change them!

jQuery is Magic

Many of jQueries perceived magic happens for designers, since many of its effects are visual whenever it manipulates the document’s HTML or CSS, which it often does. It’s also magic in the way it simplifies AJAX and the utilities jquery has are really useful but that takes us well beyond the scope of this lecture. Since it’s best to learn jQuery’s visual effects through examples, lets do that. I will use the following files in this basic tutorial.

Connect to the jQuery Library

jQuery is a collection of javascript routines stored in a library. You access those routines when using jQuery. You can host this library yourself but its more usual to let Google host it for you.

Download the compressed jQuery library to use on your site. It is one big jumble of words and symbols with everything not necessary for its execution having been removed. You can take a look at the uncompressed jQuery library if you like but unless you know Javascript, it will not make sense.

Save the compressed jQuery library in your “js” script folder with the name “jquery.min.js” and link to it:

<script src="js/jquery.min.js" type="text/javascript">

Or link to it using Google:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript">

Where to Put the Code

Both JavaScript and jQuery need to be between <script></script> tags. Though these tags can be placed anywhere in the document, jQuery scripts are usually put in the head of the document using a function that takes care of the issue in Javascript where the code can run before the web page has been loaded, because it looks at the DOM.

Javascript code, on the other hand, is usually placed at the bottom of the document, so that the scripts runs after all the elements in the body have loaded.

If the scripts are used by other web pages on the site, it is common to create an external script.js file, in the same way that you would create a central external style.css file.

<script type='text/javascript' src=js/scripts.js></script>

In the head of the document a standard script tags links to the jQuery library served by Google:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

This works when your document is on the server but not if you are developing your files locally on your hard disk. In that case, you need to include “http:” in front of the href address that Google left out. It should work fine after that.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

Why does Google leave “http:” out? That way the script will work for both http and https (http secure) sites but just know that this doesn’t work when you are developing on your desktop.

You can also download a copy of the “jquery.min.js” file and link to that.

Once you have connected to, or downloaded the jQuery library, you set up the open and closing script tags in which to embed the code:

<script type="text/javascript">

</script>

The Ready Event

Next comes the initialization function called the ready event which waits for the document to be ready before it executes the jQuery code. This does not mean that the document and all the linked elements are fully downloaded but only that the DOM is finished, which the browser creates before it starts to parse the web page.

<script type="text/javascript">
	$(document).ready(function() {

	});
</script>

The ready event starts with the dollar sign $ which stands for the jQuery object. If you want, you can replace the “$” with “jQuery” as I do in button #3 below. They are synonymous. This is where all of jQuery’s functionality is accessed from.

The jQuery object is passed a function that says, “when the document (DOM hierarchy) is loaded and ready to be manipulated, then fire off this function.” The ready event keeps jQuery from prematurely executing before the page DOM has loaded.

The Event

The jQuery library does not do anything by itself, it just enables us to do all kinds of stuff. From a designers perspective, it’s a way to capture events from the page, and then to do something, usually with CSS, like assign classes, removing classes, adding CSS to an object, or animating the CSS.

CSS does this in a limited way all by itself. The link element animates when we hover the mouse over it. You can use the hover event in jQuery but you can also use many other kinds of events. It’s able to capture that click or double click and do things other than open a link, as there are over 40 events that it can watch out for. That’s what makes it exciting.

For example, Inside the ready event, a click handler is added:

<script type="text/javascript">
	$(document).ready(function() {
		$(".jq-1").click(function() {
	});
</script>

The click handler selects the object that, when clicked, executes whatever is in its brackets. In this case, it is the effect toggle, which toggles the CSS display value.

<script type="text/javascript">
	$(document).ready(function() {
		$(".jq-1").click(function() {
		$("p").toggle();
		});
	});
</script>

Tutorial

The files for this basic tutorial.

You will want to put the following code into the header:

<style type="text/css"> 
section {width: 800px; margin: 0 auto; background: hsla(50,100%,50%,.5); padding: 40px; position: relative; left: 0;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("li.one").click(function(){
		$("h1").toggle();
	}); 
	$("li.two").click(function(){
		$("article").slideToggle({
		});
	});  
});
</script>

And in the body, have the following code:

	<section>
	<header>
	<h1>jQuery Tutorial</h1>
		<nav>
			<ul>
				<li class="one"><a href="#">Toggle Header</a></li>
				<li class="two"><a href="#">Slide Body Copy</a></li>
			</ul>
		</nav>
	</header>
	<article>
		<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. 		</p>
		<p style="display:none">Except the code itself.
		</p>
	</article>
	<footer></footer>
</section>

Functions

Functions are a way of reusing code. Much like the external style sheets are all referenced by the different pages. Functions can be called any number of times rather than having to repeat all of that code every time. Writing functions is easy:

function colorMe(){
	$("p").css("color","hsla(220,100%,50%,1)");
	$("h2").css("color","hsla(20,100%,50%,1)");
}

The empty parentheses signify to not pass it any parameters. We do not need to worry about that here. We need to call the function to use it, which we do as follows:

$("jq-1").click(function() {
	colorMe();
});

Four Buttons

The jQuery code is ready and watching the buttons to catch a click. When that happens, the corresponding code is executed. You execute the code by clicking the button.

By clicking the first button class="jq-1", all the paragraphs <p> will be toggled from visibility: default; to visibility: hidden; and vice versa, meaning that all paragraphs that are currently hidden will show.

Clicking the second button class="jq-2" toggles the site’s navigation, which is in a div with id="static".

Clicking the third button class="jq-3" will hide this slow, with this being the object being talked about in the click handler, which is the third button. It will not come back until the page is refreshed

Clicking the forth button class="jq-4" changes the CSS color value on a number of different elements. It does this by calling the function colorMe which contains the code that changes the CSS of the elements.

Test it out: 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function colorMe(){
	$("p").css("color","hsla(220,100%,50%,1)");
	$("h2").css("color","hsla(20,100%,50%,1)");
	$("pre").css("color","hsla(120,100%,50%,1)");
	$("li").css("color","hsla(170,100%,50%,1)");
	$("h1").css("color","hsla(270,100%,50%,1)");
	$("h3").css("color","hsla(320,100%,50%,1)");
	$("#site-description").css("color","hsla(320,100%,50%,1)");
}
$(document).ready(function() {
	$(".jq-1").click(function() {
		$("p").toggle();
	});
	$(".jq-2").click(function() {
		$("#static").fadeToggle();
	});
	jQuery(".jq-3").click(function(){
		$(this).hide("slow");
	 });
	$(".jq-4").click(function() {
			colorMe();
	});
});
</script>


Oh oh, You just hid all of the paragraphs. Better click the button again.

Toggle P toggles between display: default; and display: none;. The paragraphs that show up here, including this one and the one above were styled display: none;. That is why they show up while the other disappear when you click the button.

Javascript Performs on the DOM in the Browser’s Memory

If the letters in the headline are red, you clicked the Toggle P button without clicking on the Color Text button or its reset, blue if you clicked the Color Text button before toggling the paragraphs or black if you clicked the reset for the color Color Text button before clicking the first button.

This happens because Javascript does all of its work in the DOM hierarchy that the browser keeps in memory. The changes to the page are done only in memory. Whatever changes in value that jQuery makes on the DOM stay that way until the page is refreshed, in which case it requests the original values from the server and resets the DOM.

The point to take away from this is that the Browser keeps the entire web page including all of its resources in memory, and that is where Javascript’s changes take affect, changing the DOM, and thus, changing the way the page looks.

You can reset the colors if you want.

Rethinking Website Design

Major design decisions can be based on interactive code, like what happens when the code is executed on this page when clicking the buttons above.

jQuery is a powerful way to manipulate your CSS and HTML. From a designers’s point of view, it’s an extension of HTML and CSS, an amazing expansion of what’s possible over using just HTML and CSS alone.

This introduction gives you a taste of what’s possible. It will take some time to redesign your web pages once you have the power of Javascript as harnessed by jQuery under your belt. My guess is that you’ll be egging yourself on to learn jQuery after this course has finished. Linda.com has good tutorials that will help you find your way.

Examples

Javascript and jQuery scripts can often by copied, and with a few tweaks, used to add behavior to your website. The follow examples give you a place to start.

Simple Javascript Random Image Slideshow. Copy the script, paste it between the body tag, replace the images and set the delay, to something other than 1 second.

JQuery develops a number of demos and a link to a complete jQuery Image Slider. Be forwarded. There are many default options and you will have to change the parameters to make it look good. The benefit is that this slider is fully documented.

Parallax scrolling is all the rage. This means that a number of elements scroll past at different speeds. The Nike website made this famous, and here is a tutorial of how to accomplish that. It is a great tutorial on GitHubwith source code.

If you find code you like but someone has compressed their Javascript into an unreadable form, you can use beautifier to made the code readable.

Smooth Scrolling Animation

Most people are attracted seeing their webpages scroll to a location on the page, which has led to a revolution in single page designs rather than multipage designs. A very simple solution is arbitrary anchor.

A much fancier single page website template is created by Peter Finlan. Another flavor is synthethica. While it is tempting to use these ready made templates as a starting point, try to understand how jQuery (and the many other technologies) are implemented so you can do something on your own instead.

Simple jQuery Slider

Everyone asks for an image slider. This one is simple. Download demo

Add CSS styles

#gallery {width: 601px; margin: 0 auto;}
#gallery li {display: inline; margin-right: 3px;}

Add link to jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

or if on the desktop:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

Add jQuery Code

$(document).ready(function() {
	$("#gallery li img").hover(function(){
		$('#main-img').attr('src',$(this).attr('src').replace('thumb/', ''));
	});
	var imgSwap = [];
	 $("#gallery li img").each(function(){
		imgUrl = this.src.replace('thumb/', '');
		imgSwap.push(imgUrl);
	});
	$(imgSwap).preload();
});
$.fn.preload = function() {
    this.each(function(){
        $('')[0].src = this;
    });
}

Add HTML

	<div id="gallery">
	<img src="gallery/img_1.jpg" alt="" id="main-img" />
	<ul>
	  <li><img src="gallery/thumb/img_1.jpg" alt="" />
	  <li><img src="gallery/thumb/img_2.jpg" alt="" />
	  <li><img src="gallery/thumb/img_3.jpg" alt="" />
	  <li><img src="gallery/thumb/img_4.jpg" alt="" />
	  <li><img src="gallery/thumb/img_5.jpg" alt="" />
	  <li><img src="gallery/thumb/img_6.jpg" alt="" />
	  <li><img src="gallery/thumb/img_7.jpg" alt="" />
	  <li><img src="gallery/thumb/img_8.jpg" alt="" />
	  <li><img src="gallery/thumb/img_9.jpg" alt="" />
	  <li><img src="gallery/thumb/img_10.jpg" alt="" />
	
</div>

Javascript is Back

Now that the browsers have cleaned up their act, it is possible to skip the need for jQuery and do everything in Javascript. You can try the Wallop Slider. The instructions for a slider are a little more complex but it does not use the jQuery library.

The next frontier would be to develop your web site interactivity using Javascript and jQuery but it is more important that you create good websites first. Javascript requires that the website you build is well designed. That is the focus of this class, so there is no Javascript or jQuery requirement for the final.

Want to know more about javascript? Try the WesBos Javascript for Designers and make sure you get the student discount. Here is beginner’s Essential Javascript Cheat Sheet and PDF version for those who know just enough JavaScript to get them into trouble.

If you want to learn more about jQuery?, do so but you are on your own. There are advanced courses that address programming. You can also look up videos on Linda.com or explore the web.

That should not stop anyone, however, from trying it out, once you have developed some solid HTML and CSS skills, and have a working website. So here are some code snippet that can help you create well designed web sites, as Aditi Timbadia demonstrates (she implements side navigation).

Useful Javascript Snippets from W3schools

HOW TO

Tabs
Dropdowns
Accordions
Hover tabs
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Navbar hides when scrolling
Navbar shrinks when scrolling
Sticky Navbar
Mobile Navbar
Parallax
HTML Includes
Google Maps
Tooltips
Slideshow
Filter List
Sort List

11 PHP

What is PHP?

PHP was originally an abbreviation for “personal home pages” but has since been changed to “hypertext pre-processor.”

PHP is the centerpiece of website development, with over 70% of all websites using it (2022) as the server-side scripting language. Making it possible to build dynamic, database-driven websites and web applications, PHP is used by WordPress and a large number of other content management systems.

PHP is similar to a lot of other programing languages. What sets it apart is its seamless integration into HTML. The name PHP is a recursive acronym for PHP: Hypertext Preprocessor. That tells you that PHP, which resides on the server, creates HTML files from PHP scripts on the fly.

As an end user, all you see are HTML pages. PHP does its work behind the scenes on the server from which you request the page. This is different from Javascript, which is executed by the browser on the page as it is served. PHP constructs the page before javascript can act on it.

What we will do in this section, after briefly talking about some details of how PHP works, is show how PHP modularizes web development. If you want to learn more, check out codecademy

Modular Web Development

One way to think about a web site is as a collection of pages, which is what we have done up to now. CSS helps us reduce redundancy by centralizing the instructions of what each page is to look like. A centralized style sheet saves us a lot of time. PHP allows us to do the same for the different parts of the marked up content that stays the same from page to page.

A web page is composed up of modules that remain consistent throughout the site, like the header, navigation, asides, footer, etc. PHP allows us to separate these modules out as centralized external files. That means creating modules like footer, header and navigation, and useing PHP to stitch them together and serve them up as finished HTML pages.

PHP Basics

PHP resides on the server. Everything is done from the server. It runs the PHP that executes the PHP scripts that we will write.

Change the file extension of the file from .html to .php to make PHP work. To execute the PHP scripts, you need to be running the PHP interpreter. The server already runs a PHP interpreter. So you will put the files on the server to execute them.

Creating a Most Basic PHP Page

Open up a blank Editor file and write:

<!DOCTYPE html>
<?php
echo "Hello World!";
?>

This is a legitimate HTML5 document if you recall that the html, head, title and body tags are optional.

Save the file on the server, and when you open it in your browser, you will see “Hello World!” in the upper left hand corner.

You have just executed a PHP script and created an HTML page. If you look at the code, all the PHP will have disappeared. Only the HTML is left.

A few things to note about the PHP script. First, the statement starts with <?php and ends with ?>. That is how you format the PHP code, which is written between these brackets.

The statement ends in a semicolon, just like CSS statements do. That signifies to the PHP processor that the statement is complete.

Content text is called a string, and is always surrounded by quotes while working within the PHP tags, just like attribute values are in quotes inside the HTML tag. Because we are writing code, and content is something that the code works on. As there is a conflict in the way that regular writing uses certain characters, like space and return for example, and for that reason needs to be differentiated from the code.

HTML is the other way around, where all of the code is separated from the content by tags, because it’s really about the content, while a coding language like PHP is really about the code.

The last thing you see is the word echo. This is a language construct, and it is what makes PHP Hypertext friendly. It tells the PHP processor to print the HTML to the screen. Use echo to turn PHP code into HTML.

Variables

No one likes to do anything twice, and programing languages are full of ways to optimize the code. One of the most fundamental and well known tenets of software engineering is theDRY rule – don’t repeat yourself.

Just as CSS centralizes the instructions for how the web page looks, and PHP modularizes the HTML web site into a number of components, programing languages create variables and give them names to optimize the code. This is how to write the last statement using a variable:

<!DOCTYPE html>
<?php
$myString = "Hello! ";
echo $myString;
echo "I'm a PHP script!";
?>

The dollar sign $ signifies that myString is a variable, and the equal sign = assigns it to the text “Hello”. When this variable is echoed, it writes out “Hello”. The savings in this example are not exactly spectacular but you get the idea. It saves programers from having to write and update the same code over and over again.

Functions

Another way that programming optimizes is to give names to common routines that it has to perform. These are called functions. Functions are more than just a name, because they often act on information, as in this simple example.

<!DOCTYPE html>
<?php
function myGreeting($Name){
    echo "Hello there ". $Name . "!<br />";
}
myGreeting("Jane Doe");
myGreeting("John Doe");
myGreeting("Barbie");
myGreeting("Ken");
myGreeting("America");
echo "How Are You?";
?>

The computer runs down the page just as in HTML. When it gets to myGreeting, it takes the value in the parentheses and passes it to the variable “$name.” The function then operates on that variable, in this case concatenating “hello there ” with the name, an exclamation mark and a line-break element. These three things are concatenated, or brought together, by the period. The entire result is then printed, and the computer goes to the next line and repeats the entire procedure over again, till the end, where echo tells it to print “How are You?”

Operators

Computers control the flow of electrons in circuits that are either on or off. Controlling this flow gives rise to how a computer works, and how computer languages work. We say that a program is running, because even if it does nothing on the screen, the flow is cycling, waiting for something to trigger a change in the flow.

Operators manipulate this flow, using simple logic and math in creative ways. Basic logic structures the flow and determines how the result is to be assigned; if this is equal to that or this and that. There are boolean operators that signify the outcome of the flow as true or false, causal statements, that say if condition is met, do that, or else it redirects the flow in another direction, and lots of mathematical operators that go way beyond addition and subtraction.

PHP’s use is primarily connected up with databases that store the snippets of content that PHP can pre-process into HTML pages. To do that it spends a lot of the time talking to databases and requesting and looping through the content to organize it into HTML pages. We are not going to go any further into the PHP language itself but know that many of the larger sites use this or some other kind of server side scripting.

Includes

You only learn something if it is truly useful. In that way, PHP provides a very powerful function to modularize the website with a bare minimum of code:

<?php include(); ?>

Insert an HTML file name and it’s location in the brackets and the file’s content is inserted at that point.

This allows you to create often used HTML snippets only once, like the header, footer, menu and so on. Think of it as an external style sheet for HTML code.

Create common HTML like a menu file that you want all your web pages to include. When adding new pages to your site, for example, instead of having to update the links on every web page, you simply update the include file.

To create a common menu file that all our pages will use, save a blank file as “header.html” in the same directory as the index.html and paste in the header element as it exists on your website. To include the header in every page, replace the header element with the following code:

<?php include("header.php"); ?>

That’s it. When a browser makes a request for a page, it will include the code from the header.html file. You can do this with the navigation, the footer, and any other part of your web site whose content remains the same throughout the web site.

I’ve prepared an example to demonstrate that.

The one tricky thing is to give a user feedback on the page they are on. This is accomplished by adding both an id to each page and a unique class to each menu, and to write a css rule that, when they coincide, lights up the menu to highlight the current page.

Visitors do not see the PHP code. All the PHP is processed out. What remains is HTML, as if it had been written as one HTML document. Download the code

More

Forms rely on a PHP scripts. WordPress is created using PHP. There is a lot to server side scripting.

Sample code for the PHP example:

modular.php

<!DOCTYPE html>
<html lang="en"> 
<head>
<meta charset="utf-8">
<title>Modular Web Sites</title>
<link rel="stylesheet" href="style.css" media="all">
</head>
<body id="modular">
<div id="wrapper">
<?php include_once("header.php"); ?>
<section>
<?php include_once("navigation.php"); ?>
<article>
<h2>Modular Web Development</h2>
<p>One way to think about a web site is as a collection of pages, which is what we have done up to now. CSS helps us reduce redundancy by centralizing the instructions of what each page is to look like. A centralized style sheet saves us a lot of time. PHP allows us to do the same for the different parts of the web site that stay the same from page to page. 
<p>A web page is composed up of modules that remain pretty consistent throughout the site, like the header, navigation, asides, footer, etc. PHP allows us to separate these modules out as centralized external files. That means we will be creating modules like footer, header and navigation, and then use PHP to put them all together and serve them up as finished HTML pages. 
</article>
</section>
<?php include_once("footer.php"); ?>
</div>
</body>
</html>

navigation.php

<nav>
<ul>
<li><a class="whatIs" href="whatIs.php">What Is PHP?</a></li>
<li><a class="modular" href="modular.php">Modular Pages</a></li>
<li><a class="basics" href="basics.php">PHP Basics</a></li>
<li><ul>
<li><a class="page" href="page.php">Writing PHP</a></li>
<li><a class="variables" href="variables.php">Variables</a></li>
<li><a class="functions" href="functions.php">Functions</a></li>
<li><a class="operators" href="operators.php">Operators</a></li>
</ul></li>
<li><a class="includes" href="include.php">Includes</a></li>
<li><a class="more" href="more.php">More</a>
<li><a class="example" href="example.php">Example Code</a></li>
</ul>
</nav>

header.php

<header>
	<h1>Modular Websites using PHP</h1>
</header>

footer.php

<footer>
	<a href="">Web Design 1</a>, Parsons, the New School of Design. Additional resources can be found at <a href="http://PHP.net/">PHP.net</a>, with tutorials and the manual at an <a href="http://PHP.net/manual/en/intro.pdo.php">Introduction to PHP</a>. 
</footer>

CSS Styles

See the note that explains the special treatment for the navigation page highlight below.

/*structure*/
body{
	background: #aaa;
}

#wrapper {
	width: 650px;
	margin: 40px auto;
}
header {
	height: 75px;
	background-color: #eee; 
	padding: 30px 30px 0px 30px;
	border-bottom: 4px double #aaa;
}
section {
	background: #ccc;
}
article {
	background: #eee;
	padding: .5em 1em 1em;
	margin-left: 210px;
	width: 380px;
	line-height: 1.3em;
	min-height: 420px;
}
footer {
	border-top: 1px solid #aaa;
	background-color: #eee;
	padding: 30px;
}

/*Navigation*/
nav {
	width: 160px;
	padding: 20px;
	float: left;
	background-color: #eee;
}
nav ul {
	padding-left: 20px;
}
nav ul li {
	list-style: none;
	padding: 2px 0 2px 0px;
	}
/* Notice
	  All the page ids are paired up with their unique menu item. That way the link on each page light up, so you know which page you are on 
*/
body#whatIs a.whatIs,
body#modular nav ul li a.modular,
body#basics nav ul li a.basics,
body#page nav ul li a.page,
body#variables nav ul li a.variables,
body#functions nav ul li a.functions,
body#operators nav ul li a.operators,
body#includes nav ul li a.includes
{
	color: black;
	background: #fff;
}
nav ul li a{
	display: block;
	color: #000;
	text-align: left;
	padding: 10px;
	background: #ddd;
	border: 1px outset #eee;
	text-decoration: none;
}
nav ul li a:hover{
	color: black;
	background: #aaa;
}
/*style*/
h1 {
	font-size: 2em;
	font-weight: 700;
}
h2 {
	font-size: 1.5em;
	margin: 1.4em 0 .6em 0;
	font-weight: 700;
}
pre {
	background: #eef;
	padding: 1em;
	margin: 1em;
}

14 Homework

Homework for the Final

  1. Update website with suggestions from the peer review. State how effective the peer review was in making you reconsider aspects of your site.
  2. Write review and hand in to the person whose website you reviewed right after you reviewed it.

Homework for the Unit

  • The final project is to have a form on it.

10 CSS3 #2

Week 10
10/29

CSS3 part 2. More CSS3 properties: 2-D transforms, transitions, animations, multicolumn layout and Compositing and Blending properties.
Activity: Use these properties in class.
Activity: In-class Workshop.

Homework

1) For class: Use the new CSS3 properties to create a simple animatic for your final project. Animate elements created in the previous homework. 2) For final: Finish wireframe and Photoshop Comp for Final. Read chapter 14. Due: The following week.

Materials

Additional materials for this unit can be found by following these links (14 pages):

Goal

The goal of this unit is to:

  • Master the new CSS3 properties and use them.

Outcomes

At the end of this unit, students will have:

  • Been exposed to how these new properties work
  • Have practiced using these properties and are able to apply them to their own projects.
  • Have an understanding of sprites to more efficiently use images.

Step-by-Step

20 Review homework and answer questions.
30 Demo: 2D Transforms with a quick look at 3D transforms.
30 Demo: Transitions
30 Demo: Animation

10 Break
60 In-class Workshop & Review.

News and External Resources

Sources of information that will enrich your knowledge about web design and will help you to stay current:

  1. Pentagram A Seminal Design Agency. Look through their web portfolio for web design inspiration.
  2. Happy CogJeff Zeldman’s Design Company. The design agency of a well known standards compliant web design advocate.
  3. Webby Awardsaward for excellence on the Internet.

Work done In Class

10 Homework

Homework for the Final

  1. Your worksheet needs to reflect your final project, and it is due today (the work-sheet, not the final, with research, wireframe, comp and user experience profiles, including links where necessary).
  2. Create a mockup and develop a look that sells your project. This can build upon the CSS3 assignment from last week.
  3. Translate the structure of the comp into a wireframe
  4. Develop coherent user experience profiles.

Homework for the Unit

  • Using these new CSS3 properties, create an animatics or animated page that sells your project.
  • It’s possible to animate the elements created in the previous homework.
  • Make sure that you use at least two transforms, transitions and an animation.
  • Ideally you animate everything by hand, but I will understand if you use Adobe Edge.
  • A link to this promotional material has to be on the work-sheet.

10 CSS3 Animation

Apple’s Webkit team has introduced a number of technologies, one of which is CSS Animations, which allow an author to modify CSS property values over time. This is an evolving specification. Expect lots of changes as time goes by.

The good news is that animations are hardware accelerated. The computer’s graphic chip will be doing the heavy lifting, and not the CPU. This should speed animations up from the start.

Involved animations are complicated, and I’m sure that the future will develop all kinds of tools that will help facilitate building more complicated animations. To that end, there are several programs targeting the creation of CSS animations, primarily targeting the building of ads without using Flash, including Sencha’s Animator, Adobe’s Edge and andy clarke. Be aware that most of these solutions rely on javascript for their animations, but since the program is writing the code, all you need to deal with is a timeline interface.

@Keyframe

You have seen these @ rules used before, in @media, @font-face and @import. At-rules are instructions or directives to the CSS parser. The @keyframe contains the keyframes of the animation. The way to write it is:

@-webkit-keyframes name-for-animation {
  /* RULE SETS */
}

In between the brackets are the rule sets, which always start with the start and stop keyframes: from or 0% and to or 100%. The entire keyframe at rule looks like:

@-webkit-keyframes name-for-animation {
   0% /* from */{
   }
   100% /* to */ {
   }
}

All other reframes come between the start and end, and you can use from and to, or 0% and 100% keyframes. To make it work, however, you also need to include the animation name as a quality of the animation property.

In the demo below, the div with and id of “ani-1” contains the animation property shorthand that calls up the keyframe at rule. Within this property we’re specifying the name of the animation animation-name: name-for-animation, to specify which keyframes to use, the duration, animation-duration: 10s, the timing function: animation-timing-function: linear and the number of times to repeat the keyframes animation-iteration-count: infinite. There is also a direction property animation-direction: normal, and the possibility to set a delay animation-delay: 0.  

You can change the animation, but to get the demo to register the changes, you need to temporarily change the keyframe name in the animation property, and then change it back, and it will recognize any changes you’ve made to the keyframes, otherwise it will continue on its previously determined course. The animation is set up for webkit only.

CSS Code View

Animation is in its infancy, and the specification will evolve and probably change several times before it settles down, but it’s actively being implemented by all major browsers, so its here to stay. If you want to pursue CSS animations, check out CSS3 Animator for a great resource.

10 CSS3 Transitions

CSS Animations first made their appearance in Surfing Safari, the blog devoted to Apple’s Webkit browser. I had to have the most recent nightly build to see the animation, and was, of course, amazed to see leaves fall or basic shape animation (these demos only work in Webkit browsers).

That was two years ago. Since then the standards compliant browsers have picked this up and it has since been submitted as a standard.

Since the release, the transformations have been offloaded to the computer’s graphic chip, meaning that they are smoother and faster than CPU driven animation using Javascript.

Transition Between Pseudo Classes

Transitions describe how CSS properties can be made to change smoothly from one value to another over a given duration. By default, this duration for pseudo classes is instantaneous, as demonstrated by the change when hovering over this element. The change in appearance is the difference between the element’s description and the pseudo class :hover. It goes from background: purple; to background: blue; as soon as the mouse hovers over the element.

Instead of making this change instantaneously, a transition gives this change a duration. You can see that the transition property is specified as a change in the background color, with a duration of 4 seconds. The before and after states are determined by the differences in the element’s description and the description of its hover state.

CSS Code View

When you hover over the div, the transition from purple to blue takes 4 seconds.

A good use for this transition effect is to animate the opacity between two pictures.

CSS Code View

Taiyo jumping
Taiyo in the snow

Adjusting the Rate of Change

The transition velocity can be controlled. In addition to the default transition timing function, there are a number of other timing functions based on 5 predefined cubic bézier curves that control the rate of change during the transition function. Each box below has the same transformation but as you roll over the example, it demonstrates the different transition timing functions, as labeled.

You can create the rate of change curve yourself by specifying the x and y coordinates of the two bézier control handles associated with the starting and end points. In the last example, it is transition-timing-function: cubic-bezier(0,1,1,0);. An ease-in curve would be defined as cubic-bezier(0.42, 0, 1, 1); and an ease-out curve would be defined as cubic-bezier(0, 0, 0.58, 1), the first brings the curve down while the second pushes it over the linear progression of (0, 0, 1, 1). You can try this yourself by changing the numbers below and hovering over the demo above:

CSS Code View

default »
linear »
ease-in »
ease-out »
ease-in-out »
cubic-bezier »

This injects a bit of AfterEffects into web presentations, though it is much more limited in scope. There is much more promise of that with CSS3 animations.

What Attributes can be changed?

The W3 has the following list of properties that can be changed in a transition.

Some of them are:

  • background-color, image and position
  • border-color, width, length, spacing
  • color
  • crop
  • height
  • left
  • letter-spacing
  • line-height
  • margin
  • max-height
  • max-width
  • min-height
  • min-width
  • opacity
  • outline-color, offset, width
  • padding
  • right
  • text-indent, shadow
  • top
  • vertical-align
  • visibility
  • width
  • word-spacing
    integer
  • zoom

10 2D&3D Transforms

Visual Formatting Model

Illustrator coordinate system
Illustrator
Web coordinate system
web coordinate system

The web browser lays out the page according to a coordinate system that, by default, is expressed in pixels and has the X and Y Zero point in the upper left hand corner of the parent object, like InDesign. Illustrator places it on the lower right hand corner, the way you learned it in geometry.

2D Transform

The transform property modifies this coordinate space, so that elements can be translated, rotated and scaled in this two dimensional space. When you create a value for the transform property, a new local coordinate system is established by which the position of the element is calculated. The 2D transforms add up, meaning that if you rotate the parent element, and then rotate the child element, the child will be rotated in addition to the parent’s rotation. The coordinate system then calculates the cumulative transformation matrix (CTM) for the element.

You can apply two different transforms to the X and Y axis with the transform property values transform: <transform-function for X> <transform-function for Y>; where the 2D transform functions are listed in length or percentages and angles in degrees, grads, radians or turns (according to the CSS3 values and units):

  • matrix(number, number, number, number, number, number)
    Matrix specifies a 2D transformation in the form of a transformation matrix of six values. matrix(a,b,c,d,e,f) is equivalent to applying the transformation matrix [a b c d e f].
  • translate(value for x, value for y)
    translate specifies a 2D translation by the vector [tx, ty], where tx is the first translation-value parameter and ty is the optional second translation-value parameter. If <ty> is not provided, ty has zero as a value.
  • translateX(value)
    Translate X specifies a translation by the given amount in the X direction.
  • translateY(value)
    Translate Yspecifies a translation by the given amount in the Y direction.
  • scale(value for x, value for y)
    Scale specifies a 2D scale operation by the [sx,sy] scaling vector described by the 2 parameters. If the second parameter is not provided, it is takes a value equal to the first.
  • scaleX(value)
    Scale X specifies a scale operation using the [sx,1] scaling vector, where sx is given as the parameter.
  • scaleY(value)
    Scale Y specifies a scale operation using the [1,sy] scaling vector, where sy is given as the parameter.
  • rotate(angle)
    Rotate specifies a 2D rotation by the angle specified in the parameter about the origin of the element, as defined by the transform-origin property.
  • skewX(angle)
    Skew X specifies a skew transformation along the X axis by the given angle.
  • skewY(angle)
    Skew Y specifies a skew transformation along the Y axis by the given angle.
  • skew(angle, angle)
    Skew X and Y specifies a skew transformation along the X and Y axes. The first angle parameter specifies the skew on the X axis. The second angle parameter specifies the skew on the Y axis. If the second parameter is not given then a value of 0 is used for the Y angle (ie. no skew on the Y axis).

If your object is small, it is not a problem to establish its position on the default coordinate system, and tweaking its relative position if need be, but for some objects, it is better that you control the point of the transformation, which by default is the midpoint of the object.

You can set the 0,0 point to determine the point of transformation using percentage, length, or keyword like left, center and right for the X axis and top, center and bottom for the Y axis: transform-origin: left top

If only one element is is specified, the second value is assumed to be center.

Transform can be used locally or global. First, it is a local way of turning objects that does not involve the structure of the layout itself. The second way is to transform large parts of the document, and since the children inherit the parent’s transforms, all the children will take on that transformation.

Local Transforms

CSS Code View

border image
The content (children) of the transformed element inherit the altered coordinate space, and transform with it, such as this text and image.

global Transforms

Here you will transform the entire content element on this page from the center, with everything on it. Every child element gets transformed with the parent.

Change the values for both the transform origin and the transform scale, rotate, transform and skew. Careful, for you can lose the ability to edit this if you make too radical a change, and will need to refresh the page to reset it. Try rotating the element by 90°, 180° or 360 degrees.

CSS Code View

Use Cases

See the Pen
Diagonal Layouts in 2020
by Nils Binder (@enbee81)
on CodePen.

Front End Interfaces

A lot of activity is happening with these tools, and you can expect Illustrator-like drawing programs at the front end that use CSS and HTML as the backend language. Check out this text on a path generator and don’t forget to look at his explanation of Natural Object-Rotation with CSS Transform 3D and pop-up book example.

Imagine that this is only HTML markup styled with CSS!

Transition and Transform Animations

It’s possible to animate the transformations using the psudo class hover. Much like the transition effect applied to the alpha of the overlying picture to make it fade upon hover, using transformations enhance the effect.

Taiyo

Tompkins Square Park

Tutorial, Demo and Download.

3D Transform

Add to the X and Y axis a z axis, and you go from 2D to 3D. There are a number of additional 3D functions addressing the 3D space:

  • matrix3d(number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number)
    Matrix 3D specifies a 3D transformation as a 4×4 homogeneous matrix of 16 values in column-major order.
  • translate3d(value for x, value for y)
    Translate 3D specifies a 3D translation by the vector [tx,ty,tz], with tx, ty and tz being the first, second and third translation-value parameters respectively.
  • translateZ(value)
    Translate Z specifies a 3D translation by the vector [0,0,tz] with the given amount in the Z direction.
  • scale3d(value for x, value for y, value for z)
    Scale 3D specifies a 3D scale operation by the [sx,sy,sz] scaling vector described by the 3 parameters.
  • scaleZ(value)
    Scale Z specifies a 3D scale operation using the [1,1,sz] scaling vector, where sz is given as the parameter.
  • rotate3d(value for x, value for y, value for z, angle)
    Rotate 3D specifies a 3D rotation by the angle specified in last parameter about the [x,y,z] direction vector described by the first three parameters. A direction vector that cannot be normalized, such as [0,0,0], will cause the rotation to not be applied. Note that the rotation is clockwise as one looks from the end of the vector toward the origin.
    rotateX(angle) is the same as rotate3d(1, 0, 0, angle).
    rotateY(angle) is the same as rotate3d(0, 1, 0, angle).
    rotateZ(angle) is the same as rotate3d(0, 0, 1, angle), which is also the same as rotate(angle).
  • perspective(value)
    Perspective specifies a perspective projection matrix. This matrix scales points in X and Y based on their Z value, scaling points with positive Z values away from the origin, and those with negative Z values towards the origin. Points on the z=0 plane are unchanged. The parameter represents the distance of the z=0 plane from the viewer. Lower values give a more flattened pyramid and therefore a more pronounced perspective effect. For example, a value of 1000px gives a moderate amount of foreshortening and a value of 200px gives an extreme amount. The value for depth must be greater than zero, otherwise the function is invalid.

    Change the perspective on the example to 200 and see how extreme it becomes, or 500, which is much more normal. Change the rotation, and see the browser render the element as if it were in 3D space.

CSS Code View

border image

The content (children) of the 3D transformed element inherit the altered coordinate space, and transform with it, such as this text and image.

Working in 3D is inherently complex and to do it right requires some calculation and knowledge of 3D. For a better primer check out understanding CSS3D transforms and Natural Object Rotation in 3D by Eleqtiq, who also gave us the CSS3 Text Warping used above. For a 3D matrix transfom tool, check out the Matric Contruction Set by Zoltan. That should get you started.

In the mean time, more browsers are supporting transforms, so it looks like you can use it sooner than later, as long as your design falls back to something presentable on older browsers.

Pong. Remember Pong? I’m sure that most of you only know it as a museum piece. It has been resurrected by Alex Walker as a strictly HTML and CSS3 (no javascript) exercise that works.

See the Pen CSS3 Pong by Alex (@alexmwalker) on CodePen.

Take a look at these 3D animated demonstrations.

10 Animation

Apple’s Webkit team introduced a number of technologies, one of which is CSS Animations, which allow an author to modify CSS property values over time. This is an evolving specification. Expect lots of changes as time goes by.

The good news is that animations are hardware accelerated. The computer’s graphic chip does the heavy lifting, and not the CPU. This speeds animations up from the start.

Here is an example by Anthony Calzadilla:

Involved animations are complicated, and all kinds of tools will be developed to facilitate building more complicated CSS animations. In the mean time, there is a lot you can do and instructions on how to do it by adding class names to your code.

There are several programs targeting the creation of CSS animations, primarily targeting the building of ads without using Flash, including Sencha’s Animator, Adobe’s Edge and Google’s Google Web Designer . Be aware that most of these solutions rely on javascript to help with the CSS3 animations but since the program is writing the code, all you need to deal with is a timeline interface.

@Keyframe

You have seen these @ rules used before, in @media, @font-face and @import. At-rules are instructions or directives to the CSS parser.

What follows are two brackets, and all the code is entered inside. This is referred to as the “code block.”

The @keyframe code block contains the keyframes of the animation. The way to write it is:

@-webkit-keyframes name-for-animation {
  /* RULE SETS */
}

In between the brackets are the rule sets, which always start with the start and stop keyframes: from or 0% and to or 100%. The entire keyframe at rule looks like:

@-webkit-keyframes name-for-animation {
   0% /* from */{
   }
   100% /* to */ {
   }
}

All other reframes come between the start and end, and you can use from and to, or 0% and 100% keyframes. To make it work, however, you also need to include the animation name as a quality of the animation property.

Now to assign the keyframes. In the demo below, the div with and id of “ani-1” contains the animation property shorthand that calls up the keyframe at rule.

Within this property we’re specifying the name of the animation animation-name: name-for-animation, to specify which keyframes to use, the duration, animation-duration: 10s, the timing function: animation-timing-function: linear and the number of times to repeat the keyframes animation-iteration-count: infinite.

There is also a direction property animation-direction: normal, and the possibility to set a delay animation-delay: 0.  

You can change the animation but to get the demo to register the changes, you need to temporarily change the keyframe name in the animation property, and then change it back, and it will recognize any changes you’ve made to the keyframes, otherwise it will continue on its previously determined course. The animation is set up for webkit only.

CSS Code View

The animation could have been optimized. I could have used the transform property, rather than top and left, which is suppose to be faster, and use sub pixel rendering to create a more fluid experience.

Animation is in its infancy, and the specification will evolve and change several times before settling down but it’s actively being implemented by all major browsers and here to stay. If you want to peruse CSS animations, check out Lea Veroa’s Animatable for inspiration.

Interactive Stories/Ads

Digital storytelling — Designing this Interactive HTML5 Storybook is explained in detail at the end of the story.

Google recently introduced Google Web Designer and Adobe has The Edge Suite and in particular Edge Animate. These tools produce interactive content for desktop and mobile devices. See the Adobe Edge tools used to showcasethemselves.

Flash used to dominate this domain, which was used primarily for ads but was pushed out after stepping foul of Apple’s QuickTime and the popularity of the iPhone. Who wants to pay for ads that wealthy iPhone owners cannot see?

That left a vacuum that CSS3, HTML5, and Javascript are supposed to fill. CSS, HTML, and Javascript are not Flash, and as you can see, even creating basic animation is challenging.

To solve this, both programs provide a drag-and-drop, easy-to-use user interface for creating animation and interactivity using HTML, CSS, and JavaScript. Adobe wants to recapture the Flash market, and Google wants people to create ads because that is where Google makes its money. Google is an expert at the commercialization of goodwill.

Though we have access to both programs, I like the way Google Designer allows me to switch to code view and edit the parameters directly. Adobe Edge Animate requires Edge Code to look at the underlying code and may be more ambitious in the long run but it is not nearly so interesting and useful for us as Google’s Web Designer.

Google Web Designer

Download a copy and use it to do your animatic or motion enabled ad. Instructions on how to use the program can be found on the original download page.

Google Web Designer help and tutorials

SVG

SVG or scalable vector graphics, are waiting to HTML and can be animated. Illustrator can export .svg file format and those can be imported into this online app Svgartista

09 CSS3 #1

Week 9
10/22

CSS3 part 1. An examination of CSS3 properties: color, opacity, box shadow, border radius, multiple backgrounds, picture borders and gradients. Activity: Use these properties in class.

Homework

1) For class: Use CSS3 properties for a collateral piece promoting your project. It can be a sales poster, an online brochure, or an email advertisement. 2) For final: Research, brand and position for the final project, its target audience, write the copy and develop a look that incorporates the CSS3 properties covered this week. Due: The following week.

Materials

Additional materials for this unit can be found by following these links (33 pages):

Goal

The goal of this unit is to:

  • Master the new CSS3 properties and use them.
  • I expect to see these properties used in the final.
  • Turn your vision into a final website. Don’t compromise, email me if you need help to reach that goal.

Outcomes

At the end of this unit, students will have:

  • Been exposed to how popular CSS3 properties work.
  • Have practiced using these properties and can apply them to their own projects.
  • Understand graceful degradation in building their website using HTML5 and CSS3.

Step-by-Step

15 Review homework and answer questions.
15 Lecture: Graceful Degradation
50 Demo: CSS3 Basics.
10 Break
50 Demo: Background and Borders
10 Efficient use of background images

Talking Points

Topics covered in the reading:

Chapter 14: Enhancements with CSS3

  1. Understanding Vendor Prefixes 373
  2. A Quick Look at Browser Compatibility 375
  3. Using Polyfills for Progressive Enhancement 376
  4. Rounding the Corners of Elements 378
  5. Adding Drop Shadows to Text 382
  6. Adding Drop Shadows to Other Elements 384
  7. Applying Multiple Backgrounds 388
  8. Using Gradient Backgrounds 390
  9. Setting the Opacity of Elements 394

Current Practices

CSS3 is all over the web. Many of these sites also make use of jQuery, which is all the rage. We will learn more about that in a few weeks:

  • CSS Text Effects
  • Type Terms
  • 96 Elephants
  • Endless Night
  • More Sleep Design
  • Form Follows Function
  • Nolowene Nowak
  • Rainforest Protector
  • Shantell Martin
  • Women and Tech
  • fwa
  • awwards

    News and External Resources

    Sources of information that will enrich your knowledge about web design and will help you to stay current now and in the future:

    1. List ApartSeminal Web Magazine.
    2. Smashing MagazineMajor Web Magazine
    3. Design FestivalDesign magazine from Sitepoint.
    4. CSS-TricksGood web resource.
    5. HTML5 DoctorHelps cure all that ails you with learning and using HTML5. I referenced their element definitions to help you get started.

    Definitions

    These are the terms that participants should be familiar with during this unit:

    Internet Marketing article from Wikipedia

    Internet marketing, also known as web marketing, online marketing, webvertising, or e-marketing, is referred to as the marketing (generally promotion) of products or services over the Internet. Internet marketing is considered to be broad in scope because it not only refers to marketing on the Internet but also includes marketing done via e-mail and wireless media. Digital customer data and electronic customer relationship management (ECRM) systems are also often grouped together under internet marketing.

    Internet marketing ties together the creative and technical aspects of the Internet, including design, development, advertising and sales. Internet marketing also refers to the placement of media along many different stages of the customer engagement cycle through search engine marketing (SEM), search engine optimization (SEO), banner ads on specific websites, email marketing, mobile advertising, and Web 2.0 strategies.