Code excerpts

Here are some bits of code and functionality that I found myself using and reusing all the time.

Responsive design

I thought I'd start with responsive design, since it's so trendy nowadays. I can't possibly forget the first time I read about media queries, different layouts and all that malarkey was doing my head. But then, in the end I had to learn to use it. Right, so in terms of media queries, I usually have the following. For tablets:

/*Tablets*/ @media (min-width:768px) and (max-width:1023px){}
/*Mobiles*/@media (max-width:767px){}

These come from the old bootstrap and I found them pretty robust, but they also offer another set of queries (which I've never tried):

/* Large desktop */
@media (min-width: 1200px) { ... }
 
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }
							

In the HTML the following meta tag would suffice:

<meta name="viewport" content="width=device-width, initial-scale=1.0" />
							
Tab system

A while back I built a neat tab system. The only downside is that, being an horizontal tab system - unlike the one used on this site which by the way is somewhat similar code-wise - isn't really suitable for mobile devices if you have too many tabs, as they will wrap. If that's the case you can do what I did for the navigation on this site: when you are on mobile view, it turns into a drop-down selection box. Anyway, here it is (I left the original colours as bright as they were, but what's important is of course the functionality)

This is tab 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices elit erat, sit amet pellentesque erat faucibus eu. Pellentesque rutrum tortor vitae elit cursus varius. Vivamus consectetur orci viverra nisi volutpat varius. Sed blandit ligula quam, nec vehicula nisi dictum id. Phasellus volutpat porta nisl. Praesent convallis erat tellus, eget accumsan risus vulputate non. Integer tempus est mauris. Ut tempus risus nec sodales laoreet. Nullam id nisi nec tellus consequat condimentum. Nunc urna enim, sagittis feugiat diam id, congue egestas tortor. Aliquam et posuere tortor, id vulputate magna. Morbi volutpat vel risus ut dapibus. Praesent lobortis hendrerit turpis, ac tempor sapien sollicitudin eget. Mauris hendrerit molestie est, id consectetur libero fermentum nec. Donec consectetur eleifend eros et vulputate. Sed nec est ipsum.

This is tab 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices elit erat, sit amet pellentesque erat faucibus eu. Pellentesque rutrum tortor vitae elit cursus varius. Vivamus consectetur orci viverra nisi volutpat varius. Sed blandit ligula quam, nec vehicula nisi dictum id. Phasellus volutpat porta nisl. Praesent convallis erat tellus, eget accumsan risus vulputate non. Integer tempus est mauris. Ut tempus risus nec sodales laoreet. Nullam id nisi nec tellus consequat condimentum. Nunc urna enim, sagittis feugiat diam id, congue egestas tortor. Aliquam et posuere tortor, id vulputate magna. Morbi volutpat vel risus ut dapibus. Praesent lobortis hendrerit turpis, ac tempor sapien sollicitudin eget. Mauris hendrerit molestie est, id consectetur libero fermentum nec. Donec consectetur eleifend eros et vulputate. Sed nec est ipsum.

This is tab 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices elit erat, sit amet pellentesque erat faucibus eu. Pellentesque rutrum tortor vitae elit cursus varius. Vivamus consectetur orci viverra nisi volutpat varius. Sed blandit ligula quam, nec vehicula nisi dictum id. Phasellus volutpat porta nisl. Praesent convallis erat tellus, eget accumsan risus vulputate non. Integer tempus est mauris. Ut tempus risus nec sodales laoreet. Nullam id nisi nec tellus consequat condimentum. Nunc urna enim, sagittis feugiat diam id, congue egestas tortor. Aliquam et posuere tortor, id vulputate magna. Morbi volutpat vel risus ut dapibus. Praesent lobortis hendrerit turpis, ac tempor sapien sollicitudin eget. Mauris hendrerit molestie est, id consectetur libero fermentum nec. Donec consectetur eleifend eros et vulputate. Sed nec est ipsum.

The HTML is pretty simple:

<div class="tabbedMenu">
	<ul>
		<li class="active"><a href="#">Tab 1</a></li>
		<li><a href="#">Tab 2</a></li>
		<li><a href="#">Tab 3</a></li>								
	</ul>
	<div class="clear"></div>
	<div class="tabContent active">
		<h1>This is tab 1</h1>
		<p>
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices elit erat, sit amet pellentesque erat faucibus eu. Pellentesque rutrum tortor vitae elit cursus varius. Vivamus consectetur orci viverra nisi volutpat varius. Sed blandit ligula quam, nec vehicula nisi dictum id. Phasellus volutpat porta nisl. Praesent convallis erat tellus, eget accumsan risus vulputate non. Integer tempus est mauris. Ut tempus risus nec sodales laoreet. Nullam id nisi nec tellus consequat condimentum. Nunc urna enim, sagittis feugiat diam id, congue egestas tortor. Aliquam et posuere tortor, id vulputate magna. Morbi volutpat vel risus ut dapibus. Praesent lobortis hendrerit turpis, ac tempor sapien sollicitudin eget. Mauris hendrerit molestie est, id consectetur libero fermentum nec. Donec consectetur eleifend eros et vulputate. Sed nec est ipsum.
		</p>
	</div>
	
	<div class="tabContent">
		<h1>This is tab 2</h1>
		<p>
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices elit erat, sit amet pellentesque erat faucibus eu. Pellentesque rutrum tortor vitae elit cursus varius. Vivamus consectetur orci viverra nisi volutpat varius. Sed blandit ligula quam, nec vehicula nisi dictum id. Phasellus volutpat porta nisl. Praesent convallis erat tellus, eget accumsan risus vulputate non. Integer tempus est mauris. Ut tempus risus nec sodales laoreet. Nullam id nisi nec tellus consequat condimentum. Nunc urna enim, sagittis feugiat diam id, congue egestas tortor. Aliquam et posuere tortor, id vulputate magna. Morbi volutpat vel risus ut dapibus. Praesent lobortis hendrerit turpis, ac tempor sapien sollicitudin eget. Mauris hendrerit molestie est, id consectetur libero fermentum nec. Donec consectetur eleifend eros et vulputate. Sed nec est ipsum.
		</p>
	</div>
	
	<div class="tabContent">
		<h1>This is tab 3</h1>
		<p>
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices elit erat, sit amet pellentesque erat faucibus eu. Pellentesque rutrum tortor vitae elit cursus varius. Vivamus consectetur orci viverra nisi volutpat varius. Sed blandit ligula quam, nec vehicula nisi dictum id. Phasellus volutpat porta nisl. Praesent convallis erat tellus, eget accumsan risus vulputate non. Integer tempus est mauris. Ut tempus risus nec sodales laoreet. Nullam id nisi nec tellus consequat condimentum. Nunc urna enim, sagittis feugiat diam id, congue egestas tortor. Aliquam et posuere tortor, id vulputate magna. Morbi volutpat vel risus ut dapibus. Praesent lobortis hendrerit turpis, ac tempor sapien sollicitudin eget. Mauris hendrerit molestie est, id consectetur libero fermentum nec. Donec consectetur eleifend eros et vulputate. Sed nec est ipsum.
		</p>
	</div>							
</div>
							

As well as the CSS

/*TABBED MENU */
.wrapper .content .contentBox .tabbedMenu p{
	color:#070235;
	font-weight:normal;
	line-height:14px;
	font-size:11px;
}
.tabbedMenu{
	padding-left:20px;
	padding-right:20px;
	margin-top:20px;
	margin-bottom:20px;
}
.tabbedMenu ul{
	list-style-type:none;
	 margin: 0;
    padding: 0;
}
.tabbedMenu ul li a{
	text-decoration:none;
	padding:5px 15px;
	display:block;
}
.tabbedMenu ul li{
	float:left;
	margin-right:2px;
	border-top-left-radius: 10px;
    border-top-right-radius: 10px;
	/* background:url("tab.jpg") no-repeat 0 0; */
	/* IE10 Consumer Preview */ 
	background-image: -ms-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%);

	/* Mozilla Firefox */ 
	background-image: -moz-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%);

	/* Opera */ 
	background-image: -o-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%);

	/* Webkit (Safari/Chrome 10) */ 
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #FFFFFF), color-stop(1, #00A3EF));

	/* Webkit (Chrome 11+) */ 
	background-image: -webkit-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%);

	/* W3C Markup, IE10 Release Preview */ 
	background-image: linear-gradient(to bottom, #FFFFFF 0%, #00A3EF 100%);	
	
	
	/*for IE*/
	filter:progid:dximagetransform.microsoft.gradient(startColorstr='#FFFFFF',endColorstr='#00A3EF',GradientType=0);
	
}
.tabContent h1{
	margin:0;
	font-size:19px;
	color:#0c007e;
}
.tabContent{
	background-color:#def5f5;
	padding:15px;
	display:none;
}
.tabContent.active{
	display:block;
}
.tabContent p{
	margin:0;
}
.tabbedMenu ul li.active{
	filter:progid:dximagetransform.microsoft.gradient(enabled=false);
	background: none no-repeat #def5f5;
	border-top-left-radius: 10px;
    border-top-right-radius: 10px;
	
}

/*END OF TABBE MENU*/
							

And here is the script:

$(document).ready(function(){
	//alert("ohi");
	var $allTabs = $(".tabbedMenu ul li");//all the tabs
	var $allTabContent = $(".tabContent");//all the respective content
	var activeIndex;
	$allTabs.click(function(){//when a tab is clicked on
		$allTabs.removeClass("active");//remove class active from any tab
		$(this).addClass("active");//add class active to the clicked on			
		$allTabs.each(function(index){
			if($(this).hasClass("active")){//find the tab with active tab
				activeIndex = index;//get its position 
				//console.log("the index is " + activeIndex );
				$allTabContent.removeClass("active");//remove active class from all content containers
				$(".tabContent").eq(activeIndex).addClass("active");//add class active to the container that matches the index of the tab
			}			
		});
	});
	//console.log($(".tabContent p").css("line-height"));
});
							
Breaking long URLs

I came across this really recently, in fact when I was working on this site. On the mobile version, the long URLs on the Other projects page were breaking my layout. And here is the solution.

.wrapper .content .contentBox .info p a{
	-ms-word-break: break-all;
	/* Be VERY careful with this, breaks normal words wh_erever */
	word-break: break-all;
	/* Non standard for webkit */
	word-break: break-word;
	-webkit-hyphens: auto;
	-moz-hyphens: auto;
	hyphens: auto;
}						
							
Drop-down navigation script

To turn the tabbed navigation into a drop-down navigation, we need to have a select box visible only on mobile and a script that takes care of redirecting the user to the right page when the selection is made. The drop-down looks like the below (this isn't a working navigation as such, it's just a visual example, for a working one resize your browser window to mobile view and check out the main site navigation)

<div class="mobileNavigation">
	<select>
		<option>- Navigate to - </option>
		<option value="home.html">Home</option>
		<option value="about.html">About</option>
		<option value="other_projects.html">Other projects</option>
	</select>
</div>					
							

And here's the script:

var mobNav = $(".mobileNavigation").css("display");
//console.log("Display is " + mobNav);
if (mobNav == 'block'){
	//alert("dropdown nav is here");
	$(".mobileNavigation select").change(function(){
		document.location = this.value;
	});
}
							
Force mobile on desktop browser

This is an interesting one. In a few occasions, I had clients asking to have the mobile functionality (not look and feel, I'm talking about functionality here) implemented on destkop when the browser window is resized to a mobile view...no, me neither. But anyway, what does it mean? Let's look at a practical example: the mobile navigation on this site. When I first built it, it only worked on a mobile, which is to say: "look at this website on a mobile device and the navigation will work." But, if you resized your desktop browser to mobile view, the mobile navigation will be visually there, but it won't work. Why? Well, because it's not a bloody mobile device, is it?!!

So what do we get it to work? By adding a timer that continuously check whether you're viewing the page in mobile view or not: a bit of client-side computer processing involved, but hey, it works.

So let's grab our main navigation again:

<div class="mobileNav">
	<select>
		<option>- Navigate to - </option>
		<option value="home.html">Home</option>
		<option value="about.html">About</option>
		<option value="other_projects.html">Other projects</option>
	</select>
</div>
							

And add a timer that checks every 100 milliseconds whethere we are in mobile view or not and if so activates the navigation:

$(document).ready(function(){	
	/*mobile navigation*/	
	var visibleNav = setInterval(function(){	
	isVisible()},100);
	function isVisible(){
		if($(".mobileNav").is(':visible')){
			//alert("nav visible");
			activateNav();
			clearInterval(visibleNav);		
		}		
	}
)};
function activateNav(){
	$(".mobileNav select").change(function(){
		document.location = this.value;
	});
}
							
Form fields style

For one of the projects I worked on, I used Twitter Bootstrap. I'm not particularly keen on that, but it surely has some nice features (don't forget the media queries, just to mention one). The style, and even the structure, used for forms are neat, and I have to admit I've been using that all the time.

Here's an example:

And here is the code. HTML:

<div class="control-group">
	<label class="control-label" for="title">Title*</label>
	<div class="controls">
		<select id="title">
			<option>Mr </option>
			<option>Mrs</option>
			<option>Ms</option>
			<option>Sir</option>						
		</select>
	</div>
</div>
<div class="control-group">
	<label class="control-label" for="firstName">First name*</label>
	<div class="controls">
		<input id="firstName" type="text">					
	</div>				
</div>
<div class="control-group">
	<label class="control-label" for="lastName">Last name*</label>
	<div class="controls">
		<input id="lastName" type="text">
	</div>				
</div>
<div class="control-group">
	<label class="control-label" for="emailAddress">Email address*</label>
	<div class="controls">
		<input id="emailAddress" type="text">
	</div>				
</div>
<div class="control-group">
	<label class="control-label" for="confirmAddress">Re-enter email address*</label>
	<div class="controls">
		<input id="confirmAddress" type="text">					
	</div>				
</div>
							

And the CSS:

/*bootstrap-like form*/
.contentBox .info .control-group{
	margin-bottom:10px;
}
.contentBox .info .control-group .control-label {
    float: left;
    padding-top: 5px;
    text-align: left;
    width: 160px;
}
.contentBox .info .control-group .controls{
	display: block;
    margin-left: 180px;
}
.contentBox .info .control-group .controls select{
	line-height: 20px;
	*height:36px;/*for ie7*/
	*width:220px;/*for ie7*/
}
.contentBox .info .control-group select, .contentBox .info .control-group textarea, .contentBox .info .control-group input[type="text"]{
	border-radius: 4px 4px 4px 4px;
    color: #555555;
	 display: inline-block;
    font-size: 14px;
    height: 26px; 
    /* line-height: 20px; */
    margin-bottom: 0px;
    padding: 4px 6px;
    vertical-align: middle;
	background-color: #FFFFFF;
    border: 1px solid #CCCCCC;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
    transition: border 0.2s linear 0s, box-shadow 0.2s linear 0s;
	width:206px;
	box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}
/*end of bootstrap-like form*/
							

A few bits to remember here:

  • You need to specify a line-height otherwise the height of the select box won't match the one of the input fields in Safari;
  • Width-wise we need to use the border-box trick to make sure that the select box and the input fields do keep the same width:
  • IE7 obviously does its own thing and doesn't support the box-sizing property, so you need the usual hacks to get it right, as per CSS above;

box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
							

ASP.NET

As I've now started to learn ASP.NET, I thought I'd post a few bits of code that I'm sure I'll use over and over again. I wasn't sure what to start with, so, why not redoing this very site in ASP.NET? Why not? So I can play around with C#, master templates, visual studio and make it responsive too! Well, here it is:http://web-dev.azurewebsites.net/Home.aspx. One warning: as I couldn't find a good hosting provider with Microsoft servers, I chose Azure. And Microsoft told me they can't guarantee the uptime of this site as it is free hosting, so if it's down, it's not my fault!

So what's new on the ASP.NET version of this site? Well, there is a nice ASP.NET form that will forward its content to the specified email address upon submission, of course!

Sending an email with Gmail

So, how does it work? Well, here is the email script (aspx.cs file):

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;

public partial class About : System.Web.UI.Page
{
    
	protected void submitData(object sender, EventArgs e) {
		//send email
		string Subject = "Web development contact form submission";
		string nameField = name.Value;
		string titleField = title.Value;
		string emailField = email.Text;
		string enquiryField = enquiry.Value;
		string Body = "Name: " + nameField + "
" + "Title: " + titleField + "
" + "Email: "+ emailField + "
" + "Your enquiry: " + enquiryField; string ToEmail = "myemailaddress@gmail.com"; string SMTPUser = "myemailaddress@gmail.com", SMTPPassword = "xxxxxx"; SmtpClient smtp = new SmtpClient(); //smtp.UseDefaultCredentials = true; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.EnableSsl = true; MailMessage mail = new MailMessage(); mail.To.Add(ToEmail); mail.From = new MailAddress(SMTPUser); mail.Subject = Subject; mail.Body = Body; mail.IsBodyHtml = true; //if you are using your smtp server, then change your host like "smtp.yourdomain.com" smtp.Host = "smtp.gmail.com"; //change your port for your host smtp.Port = 25; //or you can also use port# 587 smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword); //smtp.Host = "smtp.gmail.com"; smtp.Send(mail); //hide form and show thank you message with no panel //contactForm.Attributes.Add("class", contactForm.Attributes["class"] + " hidden"); //thankYouMsg.Attributes.Add("class", thankYouMsg.Attributes["class"] + " active"); //hide form and show thank you msg with panel controller ContactFormPanel.Visible = false; ThankYouPanel.Visible = true; } }

So, this basically gets the form fields and the form content and send everything over to the address specified. It took me a while to do it as I had all sort of security problems with Gmail. Basically, if you take the script as it is here, it won't work, and ASP.NET will most likely return an error (at least with Gmail). Gmail security experts are a bit paranoid I think, and you might end up with an mail in your inbox saying all sort of things, like somebody tried to break in your account or that . So to get it to work you will have to follow the indications in those emails, like change your settings so that the account is "your account is no longer protected by modern security standards" (requires sign in and by the way I wouldn't recommend to do that with your own address, I'm using a test one) https://www.google.com/settings/security/lesssecureapps and that "We prevented the sign-in attempt in case this was a hijacker trying to access your account," so you'll need to have a look here as well (again it requires sign in) https://support.google.com/mail/answer/14257?p=client_login&rd=1