Month: September 2014

HTML5 Forms Reference Guide

Thanks to HTML5, forms are becoming less of a headache to construct than ever before. Browser support has never been better, especially on smartphones and tablets, making this a great time to get back to basics with constructing your own forms.

The beauty of taking advantage of new input types is that if someone’s on an antiquated browser (any version of IE–kidding of course), then the input field will default back to type=”text”.

These new input types are especially useful on mobile devices, by informing the mobile OS to serve up the most appropriate keyboard for the task whenever someone taps on a field asking for a telephone, email or web address.

Here’s a reference of all the fields I’m going to cover.

See the Pen HTML5 Form by Richard (@barkins) on CodePen.

Search

A couple of new attributes in HTML5 input tags are the placeholder and spellcheck attributes. In the past, placeholder text was accomplished with JavaScript, but now its functionality is built right it. It’s basically sample text inside the input field hinting to the user what they should do with the field. As soon as the user starts typing, the copy disappears. Additionally, in this example I set spellcheck to false indicating that the browser should not spell check whatever the user enters. May not be all that useful, but it’s nice to know we have the option.

<input type="search" id="search" placeholder="search something" spellcheck="false">

Email, URL, Telephone

If you have ever constructed a database driven website, you’ll know how frustrating it is whenever someone enters information into the database inconsistently. These new input types help in producing more consistent results from user submitted information.

Not only are you able to easily set the input field to required just by adding the word, required, but as an email type, the field will automatically check to see if the user entered the email account correctly.

<input type="email" id="email" placeholder="enter your email" required>
<input type="url" id="url" placeholder="enter your website address">
<input type="tel" id="tel" placeholder="enter your phone number">

Datalist

Screen Shot 2014-09-29 at 2.44.14 PM

In effort to make forms less cumbersome to the user, you’re able to now add a list of possible values a user may enter, expediting the process of filling out a form. In the following example, I created a list of colors a user may enter. As they type their favorite color, a suggestion of possible options appear.

Here’s how to construct a list of suggestions.

  <datalist id="colors">
    <option>red</option>
    <option>green</option>
    <option>blue</option>
    <option>yellow</option>
    <option>orange</option>
  </datalist>

And here’s the input field referencing the list of options.

<input type="text" id="datalist" list="colors" placeholder="Your favorite color">

Range

The range input is also very useful in cases when you want to store consistent and specific information in the database without running into a risk of a user entering something by mistake.

<input type="range" id="range" max="100" min="0" value="10" step="10">

Date

Screen Shot 2014-09-29 at 2.45.03 PM

This is a cool feature built into modern browsers. Yet another example of something that use to be time consuming constructing with JavaScript, a calendar picker, no scripting at all.

<input type="date" id="date">

Color

Screen Shot 2014-09-29 at 2.45.46 PM

The color picker, just like the calendar picker is also very useful, but alas from my experience doesn’t have the same support on smartphones that it does on the desktop.

Wrapping it Up

And just like that, with no JavaScript you’re able to create a fast, user friendly forms. Just keep in mind however, this isn’t supported on older browsers, therefore if you think you’re going to receive a lot of visitors on older browsers, be careful with input fields that require precise information to be entered. You may need to resort to JavaScript solutions as a precaution.

Filed under: HTML5

Sticky Header with jQuery slideDown()

If your webpage gets long, you may have the desire to keep some form of branding on your website for readers to always see as they scroll through your content. This approach achieves that in a subtle yet effective way without being overly pushy.

Here it is in action.

See the Pen Sticky Header by Richard (@barkins) on CodePen.

You can apply these principles to other elements on your webpage, but I recommend using this technique judiciously and not over do it. Sticky elements on a page can oftentimes have unintended side effects, which I’ll cover briefly at the end.

HTML

Nothing out of the ordinary in the HTML, just straightforward HTML5 tags for the header and article areas.

<header id="header">
  <h1>Sticky Header</h1>
</header>

<article>
  
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam tempus dui nisi, a tincidunt nisi consequat id. Donec auctor tortor rhoncus hendrerit.......</p>

<p>....</p>
<p>....</p>
<p>....</p>
  
</article>

CSS

For styling, the only element you’ll really need is a sticky class with the following properties.

.sticky {
  position:fixed;
  display:none;
}

Additionally, the header should be styled so that its width is 100%, or you will need to add that width size to the sticky class. I’ll leave it up to you to see what happens if you don’t set a width to 100%.

Here’s all the CSS put together.

* {
  box-sizing:border-box;
  font-family:sans-serif;
}

body {
  margin:0;
  background:#c6c6c6;
}

#header {
  background:rgba(47,85,131,.9);
  padding:25px;
  text-align:center;
  color:#FFF;
  width:100%;
}

.sticky {
  position:fixed;
  display:none;
}

article {
  padding:25px;
}

jQuery

We start with creating a function that will store some position values, along with the element we want to be sticky.

var stickyHeader = function(){
  //THE POSITION OF TOP OF PAGE IN BROWSER WINDOW
  var windowTopPosition = $(window).scrollTop();
  
  //THE POSITION OF ARTICLE TOP
  var triggerContainer = $('article').offset().top;

  //THE THING THATS STICKS
  var stickyContainer = $('#header');
}

Next up, we’ll need to test if the position of windowTopPosition is greater than triggerContainer and if it is, go ahead and add the sticky class to the container we want to be sticky.

  if (windowTopPosition > triggerContainer) {    
    stickyContainer.addClass('sticky');
    stickyContainer.slideDown('fast');
    
  }else{
    stickyContainer.removeClass('sticky');
    stickyContainer.css("display","");
  }

If you noticed in the CSS previously, I included display:none in the sticky class styling, it’s because I also wanted it to slide down when the container became sticky. Otherwise the transition from non-sticky to sticky header can be a bit jarring.

This occurs when the if/else statement is true, I also included a stickyContainer.slideDown('fast'); which in effect brings the container out of hiding with a nice animation.

One key thing here is, if the user goes back to the top, although the sticky class will be removed, the display:block portion left behind by slideDown() will remain, destroying the slideDown() effect.

This is why I included the following jQuery function to fix it.

stickyContainer.css("display","");

Of course none of this function will work unless we trigger it somehow and we do that whenever the user scrolls on the page, like so.

$(window).scroll(stickyHeader);

Here’s the whole jQuery code put together.

var stickyHeader = function(){
 
  //THE POSITION OF TOP OF PAGE IN BROWSER WINDOW
  var windowTopPosition = $(window).scrollTop();
  
  //THE POSITION OF ARTICLE TOP
  var triggerContainer = $('article').offset().top;

  //THE THING THATS STICKS
  var stickyContainer = $('#header');
  
  if (windowTopPosition > triggerContainer) {    
    stickyContainer.addClass('sticky');
    stickyContainer.slideDown('fast');
    
  }else{
    stickyContainer.removeClass('sticky');
    stickyContainer.css("display","");
  }
  
  
};

$(window).scroll(stickyHeader);

You may now think you can apply this technique to other elements on your page, but be warned, whenever you apply a fixed styling to an element, the element gets moved out of its container and may end up covering up portions of content on your site. You have been warned.

Filed under: CSS3, HTML5, jQuery

Sketchbook with HTML5 Canvas and jQuery

Here’s how to build a drawing space on your website using the HTML5 canvas tag. This article will cover the very basics of getting started with canvas, but you’ll soon see how you’ll be able to take it even further.

Here’s a demo of this project.

See the Pen Sketchbook with the Canvas Tag by Richard (@barkins) on CodePen.

HTML

The only key tag in the HTML to take notice of is, you guessed it, canvas. You will need to include the width and height directly inside the tag, like so:

<canvas width="450" height="500" id="canvas"></canvas>

I included an id with the tag to reference later.

Here’s the rest of the HTML that houses the canvas tag.

<section>
<header>
  <h1>Sketchbook with the Canvas Tag</h1>
</header>

<article>
  
  <canvas width="575" height="300" id="canvas"></canvas>
  
  <div id="marker-container">
  
    <h2>Change Marker Width</h2>
  
    <input id="marker" type="range" max="10" min="1" value="1">
    
    <div id="shape"></div>   
    
  </div>  
  <button id="clear">Clear Sketchbook</button>
  
</article>
</section>

CSS/SCSS

I took advantage of a bit of SCSS here, just for time saving purposes. The only unusual item in the CSS is how I styled the ‘gradual increase symbol’ with border styling. Anytime you can substitute an image with some CSS, do it. It’s just good practice.

#shape {
  width: 0;
  height: 0;
  border-left: 125px solid transparent;
  border-right: 0px solid transparent;
  border-bottom: 15px solid #999;
  margin:5px auto;
}

Here’s all the CSS/SCSS.

Note: Check back soon on an article about getting up to speed with SASS (SCSS).

* {
  box-sizing:border-box;
  font-family:sans-serif;
}

h1 {
  color:#cc3300;
  margin:0 0 25px;
  font-size:2rem;
}

section {
  max-width:650px;
  margin:25px auto;
  background:#CCC;
  padding:25px;
  border-radius:10px;
  text-align:center;
  canvas {
    background:#FFF;
    border-radius:10px;
    box-shadow:0 0 15px #999;
    cursor:crosshair;
  }

  #marker-container {
    max-width:300px;
    background:#333;
    margin:25px auto;
    padding:15px;
    border-radius:10px;
    h2 {
      color:#FFF;
      margin:0 0 15px;
      font-weight:normal;
      font-size:1.2rem;
    }
  }
}

#clear {
  font-size:1rem;
  background:#cc3300;
  color:#FFF;
  border:0;
  padding:10px;
  border-radius:5px;
  cursor:pointer;
  &:hover {
    background:#FFF;
    color:#cc3300;
  }
}

#shape {
  width: 0;
  height: 0;
  border-left: 125px solid transparent;
  border-right: 0px solid transparent;
  border-bottom: 15px solid #999;
  margin:5px auto;
}

jQuery

Now the interesting part, some jQuery to help us interact with the canvas tag.

We’ll start off by creating some variables we’ll use throughout the program. The first one, marker will be used to store the color of the, well marker. The second variable, markerWidth will store the default width of the marker.

The last two variables I’ll cover in a bit, just include them for now.

var marker = "rgb(0,0,0)";
var markerWidth = 1;

var lastEvent;
var mouseDown = false;

Next up, we’ll need a function to setup the width of the marker working in tandem with the new HTML5 input type of range. Whenever $("#marker") is changed, like when a user moves the slider, the function changeWidth initiates and sets the current value to markerWidth.

var changeWidth =  function(){  
  markerWidth = $("#marker").val();
  console.log(markerWidth);
};

$("#marker").change(changeWidth);

Now we’ll need to set up the context of the canvas so that we can interact with it. This is fairly boilerplate stuff, you’ll need to include it in order to interact with the canvas tag.

var context = $('canvas')[0].getContext('2d');
var $canvas = $('#canvas');

Here’s a series of function that will activate whenever a user mouses down, moves the mouse and mouses up.

We’ll need to capture the canvas’ event in the DOM so that we can interact with properties of the canvas, which is why we passed an argument, e, through the function like so.

Next, set the mouseDown to true so that the following function will only work if it’s true. In the last function, we’ll set it back to false when the user mouses up so your cursor will stop drawing on the canvas then.

$canvas.mousedown(function(e){
    lastEvent = e;
    mouseDown = true;
    console.log(lastEvent);
})

If you look at the console now, after mousing down over the canvas tag, you’ll see the following properties you can use. That’s why the console.log(lastEvent) is there.

It should look something like this:

mouseevent

Notice, offsetX and offsetY?

We’ll use that information in the second function that initiates whenever a user mouses over the canvas tag.

mousemove(function(e){
  if(mouseDown){
    context.beginPath();
    
    context.moveTo(lastEvent.offsetX,lastEvent.offsetY);
    context.lineTo(e.offsetX,e.offsetY);
    context.lineWidth=markerWidth;
    context.strokeStyle = marker;
    context.lineCap='round';
    context.stroke();
    
    lastEvent = e;
  }
  
})

Since earlier we stored the context of the canvas in the context variable, we can access its properties. Such as setting the color of the stroke, context.strokeStyle = marker;, and then width of the stroke, context.lineWidth=markerWidth;.

Note: Here’s a full list of properties available for the canvas tag.

To finish this off, our last function disables drawing on the canvas after the user mouses up, like so:

.mouseup(function(){
  mouseDown = false; 
});

Here’s all the jQuery put together:

var marker = "rgb(0,0,0)";
var markerWidth = 1;

var lastEvent;var mouseDown = false;

var changeWidth =  function(){  
  markerWidth = $("#marker").val();
  console.log(markerWidth);
};

$("#marker").change(changeWidth);

var context = $('canvas')[0].getContext('2d');
var $canvas = $('#canvas');

$canvas.mousedown(function(e){
    lastEvent = e;
    mouseDown = true;
    console.log(lastEvent);
}).mousemove(function(e){
  if(mouseDown){
    context.beginPath();
    
    context.moveTo(lastEvent.offsetX,lastEvent.offsetY);
    context.lineTo(e.offsetX,e.offsetY);
    context.lineWidth=markerWidth;
    context.strokeStyle = marker;
    context.lineCap='round';
    context.stroke();
    
    lastEvent = e;
  }
  
}).mouseup(function(){
  mouseDown = false; 
});

The key takeaway here is how we assigned the markerWidth variable to context.lineWidth. You can also do the same with context.strokeStyle = marker; and I’ll leave you to figure how to evolve this project even further.

Filed under: CSS3, HTML5, jQuery, Sass

Horizontal Responsive Menu

It’s easier than you think to create a simple horizontal responsive menu with just some CSS3 media queries and jQuery. This example doesn’t include any multi-tier drop downs, but for the sake of keeping things simple, here’s a great solution. No plugin required.

The Completed Product

See the Pen Simple Responsive Horitzontal Menu by Richard (@barkins) on CodePen.

In the above embed, you’re looking at the mobile version of the menu. Check out the full screen demo and resize the browser window to see it in action.

HTML

The HTML for this simple menu is relatively straightforward. Wrapped in a NAV tag, you’ll need to include the actual menu wrapped in a DIV so that you can targeted it later. Additionally, you’ll need to include the trigger link.

<nav>
  <a href="/" id="trigger">Menu</a>
  
  <div id="menu">
  <a href="/">Home</a><a href="/">About</a><a href="/">Information</a><a href="/">Contact</a></div>
</nav>

CSS

The only key item in the CSS is the media query section, otherwise you’re free to style the list of menu links however you like. Here’s my example.

* {
  box-sizing: border-box;
}

#trigger {
  background:#cc3300;
  padding:15px;
  color:#FFF;
  text-decoration:none;
  text-transform:uppercase;
  display:inline-block;
  width:100%;
  
  display:none;
}

nav {
  background:#CCC;
  text-align:center;
  padding:5px;
  font-family:sans-serif;
}

#menu {
  background:#999
}

#menu a{
  display:inline-block;
  background:#999;
  padding:15px;
  color:#FFF;
  text-decoration:none;
  text-transform:uppercase;
}

#menu a:hover {
  background:#666;
}

@media screen and (max-width:760px){
  #trigger {
    display:block;
  }
  #menu {
    display:none;
  }
  #menu a {
    display:block;
  }
}

@media screen and (min-width:760px){
  #menu {
    display:block !important;
  }
}

jQuery

I find it’s best to utilize the “slideToggle” function in jQuery to determine the height of the menu links container. I recall seeing examples of this where the jQuery had to find out the height of all the links once revealed, but that’s not very good future proofing. If you add more links, it will cause issues.

You first start by creating the trigger by selecting the “trigger” ID and add an ON function to toggle the menu to show and hide whenever a user clicks on the trigger.

Note: Include the “preventDefault” function inside the click event so that the browser doesn’t try to following the href inside the trigger link. Alternatively, you can create a button instead of a link, but that’s up to you and your browser support (HTML5 compatibility) needs.

$('#trigger').on("click", function(e){
  e.preventDefault();
  $('#menu').slideToggle('fast');
});

And that’s all folks!

Filed under: CSS3, HTML5, jQuery

Simple To-Do App with JavaScript Only

Although the jQuery library has been a fantastic tool used by almost every front-end developer, it’s still worth taking sometime and understanding how JavaScript works. Using newly established JavaScript functions, it’s almost as simple to create basic applications with JavaScript as it is with jQuery.

Additionally, understanding fundamental JavaScript techniques will go a long way in helping you understand how to build even more complicated jQuery applications.

The To-Do App Project

In short, this project consists of new JavaScript functions that will help interact with the dom. Here’s what the completed application looks like.

See the Pen Simple Todo App with JavaScript Only by Richard (@barkins) on CodePen.

Before we began coding any JavaScript, lets start by putting together the HTML structure. I’m going to build everything into a SECTION tag which will contain an INPUT for a new task, a list of incomplete tasks and a list of complete tasks with a delete BUTTON.

HTML

<section class="container">
  
  <h1>To-Do App</h1>
  
  <div class="new-task-container box">
  
  <label for="new-task">Add New Task</label>
  <input type="text" id="new-task">
    <button id="addTask">Add Task</button>
  
  </div>
  
  <div class="todo-list box">
  
    <h2>Incomplete Tasks</h2>
    <ul>
      <li><input type="checkbox"><label>Task Name</lable></li>
      <li><input type="checkbox"><label>Task Name</lable></li>
      <li><input type="checkbox"><label>Task Name</lable></li>
    </ul>
  
  </div><!--/todo-list-->
  
  <div class="complete-list box">
    
    <h2>Completed Tasks</h2>
    <ul>
      <li>Task Name <button class="delete">Delete</button></li>

    </ul>   
    
  </div><!--/complete-list-->
</section><!--/container-->

CSS

There are a number of ways to style this, but for my demo I’m showcasing as basic of a design as possible, just for presentation purposes.

* {
  box-sizing: border-box;
}

.container {
  background:#d3efdf;
  padding:25px;
  max-width:760px;
  margin:25px auto;
  overflow:hidden;
  border-radius:10px;
  border:4px solid #b1c9bb;
  font-family: sans-serif;
}

h1, h2 {
  margin:0;
  text-align:center;
  text-transform:uppercase;
 
}

h2 {
  font-size:20px;
  text-align:center;
  border-bottom:1px solid #b1c9bb;
  padding: 0 0 10px;
  color:#57635c;
    
}

.new-task-container {
  text-align:center;
}

.box {
  padding:10px 15px;
  border:2px solid #b1c9bb;
  border-radius:5px;
  background:#FFF;
  margin:15px 0;
}


.todo-list {
  float:left;
  width:46%;
}

.complete-list {
  float:right;
  width:46%;
}

ul {
  list-style:none;
  padding:0;
  margin:0;
}

li{
  padding:10px;
  border-bottom:1px dotted #CCC;
}

.delete {
  float:right;
}

JavaScript

Here’s the fun part, good old (new) JavaScript. Start off by assigning variables you plan on using throughout the project.

  • newTask – Store the input with the id of “new-task” which we will use to grab whatever was typed into the field.
  • addTaskBtn – Store the button used to initiate adding the task to the to-do list.
  • toDoUl – This variable will store the unordered to-do list of LIs.
  • completeUl – You guessed, this variable will store the unordered list of completed tasks.
//SELECT ELEMENTS AND ASSIGN THEM TO VARS
var newTask = document.querySelector('#new-task');
var addTaskBtn = document.querySelector('#addTask');

var toDoUl = document.querySelector(".todo-list ul");
var completeUl =  document.querySelector(".complete-list ul");

Next up, we’ll want to create our first functions. This function will create the new task. It will generate the LI HTML element, the input field and the label.

Once it’s complete constructing the list item with the newly entered task by the user, it will return the result back to the function. In other words, once this function finishes running, you can call it to grab its result. We’ll cover that soon.

//CREATING THE ACTUAL TASK LIST ITEM
var createNewTask = function(task){
  console.log("Creating task...");
  
  //SET UP THE NEW LIST ITEM
  var listItem = document.createElement("li"); //<li>
  var checkBox = document.createElement("input"); //checkbox
  var label = document.createElement("label"); // <label>
  
  
  //PULL THE INPUTED TEXT INTO LABEL
  label.innerText = task;
  
  //ADD PROPERTIES
  checkBox.type = "checkbox";
  
  //ADD ITEMS TO THE LI
  listItem.appendChild(checkBox);
  listItem.appendChild(label);
  //EVERYTHING PUT TOGETHER
  return listItem;    
};

Now that we’ve constructed our new task item, all with the LI, the INPUT and CHECKBOX, we’re ready to actually add it to the to-do list.

As you’ll notice through out this application, I use a lot of “console.log()” functions to output text into the console so that I can see if things are working as they should. It’s just a good problem solving technique.

This function runs the previous function we created which then returns the result and stores it into the listItem variable. It then appends (adds) to the listItem variable to the children of the toDoUl variable we created at the start.

Here’s what that function looks like.

//ADD THE NEW TASK INTO ACTUAL INCOMPLETE LIST
var addTask = function(){
  console.log("Adding task...");
  //FOR CLARITY, GRAB THE INPUTTED TEXT AND STORE IT IN A VAR
  var listItem = createNewTask(newTask.value);
  //ADD THE NEW LIST ITEM TO LIST
  toDoUl.appendChild(listItem); 
  //CLEAR THE INPUT
  newTask.value="";
  
  //BIND THE NEW LIST ITEM TO THE INCOMPLETE LIST
  bindIncompleteItems(listItem, completeTask);
};

Now that we have the function created that pulls the newly entered task into the to-do list. We’ll need to create a function that allows the user to hit the checkbox and have the item move to the completed list.

When the user hits the checkbox, the completeTask function will launch (we’ll cover further down). Using the this we can reference the element’s parentNode which happens to be the LI it’s stored in.

Since the completed list has a delete button, we’ll need to create it here and also remove the checkbox from the list item.

Once the delete button has been created and the checkbox removed, we can have the function add the newly completed list item to the completed tasks list.

Lastly, since the the completed task list has now changed, we’ll need to rebind the elements in that list so that we can reference them later.

var completeTask = function(){
  
  //GRAB THE CHECKBOX'S PARENT ELEMENT, THE LI IT'S IN
  var listItem = this.parentNode;
  
  //CREATE AND INSERT THE DELETE BUTTON
  var deleteBtn = document.createElement("button"); // <button>
  deleteBtn.innerText ="Delete"; 
  deleteBtn.className = "delete";
  listItem.appendChild(deleteBtn);
  
  //SELECT THE CHECKBOX FROM THE COMPLETED CHECKBOX AND REMOVE IT
  var checkBox = listItem.querySelector("input[type=checkbox]");
  checkBox.remove();
  
  //PLACE IT INSIDE THE COMPLETED LIST
  completeUl.appendChild(listItem); 
  
  //BIND THE NEW COMPLETED LIST
  bindCompleteItems(listItem, deleteTask);
  
};

The deleteTask function is the simplest function here. It grabs the parent of the delete button and removes it using the JavaScript function, removeChild.

//DELETE TASK FUNCTIONS
var deleteTask = function(){
  console.log("Deleting task...");
  
  var listItem = this.parentNode;
  var ul = listItem.parentNode;
  
  ul.removeChild(listItem);  
};

Whenever we interact with both lists, we’ll have to run a function that will remind all the list items so that we can continue interacting with them.

In other words, whenever webpage first loads, the functions will see all the HTML elements. However, if we start adding and removing elements, the webpage no longer knows that those elements have been add or removed. Therefore we need the following set of functions to continuously rebind changes on the page.

//A FUNCTION THAT BINDS EACH OF THE ELEMENTS THE INCOMPLETE LIST

var bindIncompleteItems = function(taskItem, checkBoxClick){  
  console.log("Binding the incomplete list...");
  
  //BIND THE CHECKBOX TO A VAR
  var checkBox = taskItem.querySelector("input[type=checkbox]");
  
  //SETUP EVENT LISTENER FOR THE CHECKBOX
  checkBox.onchange = checkBoxClick;  
}; 


//A FUNCTIONM THAT BINDS EACH OF THE ELEMTS IN THE COMPLETE LIST
var bindCompleteItems = function(taskItem, deleteButtonPress){
  console.log("Binding the complete list...");
  
  //BIND THE DELETE BUTTON
  var deleteButton = taskItem.querySelector(".delete");
   
  //WHEN THE DELETE BUTTIN IS PRESSED, RUN THE deleteTask function
  deleteButton.onclick = deleteButtonPress;
    
};


for(var i=0; i < toDoUl.children.length; i++) {
  bindIncompleteItems(toDoUl.children[i], completeTask);
}

for(var i=0; i < completeUl.children.length; i++) {
  bindCompleteItems(completeUl.children[i], deleteTask);
}

And finally the last function of the project, the one that starts it all. This event listeners waits until a user hit the add task button and launches the addTask function.

addTaskBtn.addEventListener("click", addTask);
Filed under: CSS3, HTML5, JavaScript