March 28, 2024

11 JavaScript Code Snippets for Dynamic Web Projects

The practice of frontend web development has grown into an enormous topic of discussion. User interface designers have been working up to this point for years, and our modern era of web design has finally adopted a set of tools which are accepted universally. You can build very impressive websites using just plain HTML5/CSS3/JavaScript.

featured image - JavaScript coding web development snippets

Recently I had put together a small collection of code snippets for web designers to use for HTML5 and CSS3 techniques. In this article I have put together 11 templates for simple JavaScript development. These should work perfectly within all web browsers supporting common scripting languages. But feel free to run some test demos in your own projects or using a web interface such as jsFiddle.

1. Open a Popup Window

This is a very simple line of code but helpful in certain instances. There are many times you will want to open a Flash player for audio, video, or some other type of popup window. Using JavaScript you can setup the terms and settings for the new window to appear.

window.open("http://webdesignledger.com","newWindow");

Source

You probably will not need this code for all of your projects, but it is handy to have around. Most JavaScript developers who have been coding for years will begin to memorize this stuff as it pops up. Plus you may customize all the different parameters towards window location and dimensions.

2. Detect When Browser is Closed

If your users are going to click the close button you may want to be notified in advance. Some more annoying websites will really push this functionality for their own marketing needs. Generating popup ads or alert boxes to keep the user stuck on their page a little longer – not the best way to go about it.

function checkBrowser() {
  // triggers on clicking the close button, Alt+F4 , File->Close  
  if(window.event.clientX < 0 && window.event.clientY < 0) {
    window.open("somefile.html", "closewindow",'left=12000,top=1200,width=120,height=50');
  }
}

Source

But there are other more useful features you can do this with detection. As an example you may want to clear out a user’s cookie session immediately before closing the window. This could be for your own security reasons, and to stop anyone else from accessing a different user’s account by mistake.

3. Obtain Select Input Value

When coding over dynamic HTML forms it is a simple process to pull the value of most input fields. Dealing with things like radio buttons and checkboxes, text fields, and single-line inputs are the easiest. But what about grabbing the currently selection option from an HTML select menu?

<select id="menulist">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

<script>
var e = document.getElementById("menulist");
var optvalue = e.options[e.selectedIndex].value; // the option value attribute
var opttext  = e.options[e.selectedIndex].text; // internal text inside option element
</script>

Source

You can use this snippet for validating your code or submitting content via Ajax. There are a number of reasons to access form data before submission. Or to even stifle the submission process and pass the data manually into a backend script! The options are practically limitless.

4. Browser Detection

I often read about programmers working to detect browser software on the backend. And many times this could be useful when coding in PHP, Ruby, Python or whatever. But JavaScript can be just as powerful with browser detection methods.

// Internet Explorer
var ie  = document.all != null;  //ie4 and above
var ie5 = document.getElementById && document.all;
var ie6 = document.getElementById && document.all&&(navigator.appVersion.indexOf("MSIE 6.")>=0);

// Netscape
var ns4 = document.layers != null;
var ns6 = document.getElementById && !document.all;
var ns  = ns4 || ns6;

// Firefox
var ff  = !document.layers && !document.all;

// Opera
var op  = navigator.userAgent.indexOf("opera")>0;
var op7 = op && operaVersion() <= 7;
var op8 = op && operaVersion() >= 8;

// Detects the Opera version
function operaVersion() {
	agent = navigator.userAgent;
	idx = agent.indexOf("opera");	
	if (idx>-1) {
		return parseInt(agent.subString(idx+6,idx+7));
	}
}

Source

This quick snippet of code is easily digestible for advanced and beginning developers. The browser detection script can even include older Netscape browsers for people running that engine. I have found that squashing specific browser bugs is a struggle worth fighting.

5. JavaScript Cookies

Recently I stumbled onto a brilliant script for cookie management all based in regular JavaScript. This is a fairly long snippet consisting of four unique functions, but they can be a lifesaver working with cookies. Anybody who is just getting started as a developer could learn a lot from this code.

function setCookie(name, value) {
  if(name != '')
    document.cookie = name + '=' + value;
}

function getCookie(name) {
  if(name == '')
    return('');

  name_index = document.cookie.indexOf(name + '=');

  if(name_index == -1)
    return('');

  cookie_value =  document.cookie.substr(name_index + name.length + 1, document.cookie.length);

  //All cookie name-value pairs end with a semi-colon, except the last one.
  end_of_cookie = cookie_value.indexOf(';');
  if(end_of_cookie != -1)
    cookie_value = cookie_value.substr(0, end_of_cookie);

  //Restores all the blank spaces.
  space = cookie_value.indexOf('+');
  while(space != -1) { 
    cookie_value = cookie_value.substr(0, space) + ' ' + 
    cookie_value.substr(space + 1, cookie_value.length);

    space = cookie_value.indexOf('+');
  }

  return(cookie_value);
}

Source

These functions behave as setter/getter methods for your cookie management. Just by calling the setCookie function you may pass a name and a value pair. Then by using this name again into getCookie you may retrieve the unique value ID.

6. Detecting the Operating System

From the earlier snippet about browsers we can also look into the computer’s Operating System. JavaScript has access to the navigator property which can give us some details about the machine. You can use this to display specific download buttons or icons based on Mac or Windows users, respectively.

var system = navigator.appVersion;
if (navigator.appVersion.indexOf("Mac") != -1 ) OS = "Mac";
else if (navigator.appVersion.indexOf("PowerPC") != -1 ) OS = "Mac";
else if (navigator.appVersion.indexOf("Win") != -1 ) OS = "Win";
else if (navigator.appVersion.indexOf("SunOS") != -1 ) OS = "Solaris";
else  OS = "Linux";

//Determine Browser Version
bName = navigator.appName;
bVer  = parseInt(navigator.appVersion);

if (OS == "Mac" && bName=="Netscape") { 
  // your code here
}
else if (OS =="Mac" && bName=="Microsoft Internet Explorer") { 
  // your code here
}
else if (OS =="Win" || OS == "Linux" && bName == "Netscape") {
  // your code here
}
else if (OS =="Solaris" && bName=="Netscape") {
  // your code here
}
else if (OS =="Win" || OS == "Linux" && bName=="Microsoft Internet Explorer") {
  // your code here
}

Source

Now this code snippet will also help you determine the current browser engine, too. That isn’t necessary if you don’t want to couple these ideas together. I also ran into an excellent post on StackOverflow discussing how to parse for different versions of Windows. The answer is great at explaining a solution for determining between Windows 2000, XP, Vista, and Win7.

7. Detecting Mobile Devices

Now we can even take this code a step further at looking into newer mobile computers. Aside from responsive web design there are still plenty of mobile website layouts. Larger networks such as Twitter and Facebook have their own mobile design specifically for smartphones.

var isMobile = {
  Android: function() {
    return navigator.userAgent.match(/Android/i);
  },
  BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
  },
  iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  },
  Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
  },
  any: function() {
    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};

// Examples
if( isMobile.any() ) alert('Mobile');
if( isMobile.iOS() ) alert('iOS Device');

Source

With this code snippet you can quickly determine the Operating System of your visitor’s mobile device. This may not have a huge impact in performance. But you could alter the layout styles and display content accordingly.

8. Browser Window Dimensions

Speaking about mobile and responsive designs the dimensions of the user’s browser window may come in handy for some developers. The snippet below is a quick and easy method for determining the full height and width of the current browser window. The current script will output HTML but you can change this into any return value.

function report() { 
  document.getElementsByTagName('output')[0].innerHTML = 'screen.width:'+screen.width+'<br>screen.height:'+screen.height+'<br>window.innerWidth:'+window.innerWidth+'<br>window.innerHeight:'+window.innerHeight+'<br>window.outerWidth:'+window.outerWidth+'<br>window.outerHeight:'+window.outerHeight+'<br>document.documentElement.<br> clientWidth:'+document.documentElement.clientWidth+'<br>document.documentElement.<br> clientHeight:'+document.documentElement.clientHeight+'<br>window.devicePixelRatio:'+window.devicePixelRatio; 
}
window.addEventListener('load', report, false);
window.addEventListener('resize', report, false);
window.addEventListener('orientationchange', report, false);
window.addEventListener('deviceorientation', report, false);
window.addEventListener('MozOrientation', report, false);

Source

9. Get URL Parameter

This is a custom JavaScript function written with just a few lines of code. There may be times where you need to access the parameters passed into your browser via URL. This function will setup an array of results paired into name/value sets.

function getUrlParam(name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return (results && results[1]) || undefined;
}

Source

Try to use this code sparingly as it is needed. Backend languages are built to handle these type of query parameters and it’s good security practices to not pass over any secure data via the frontend interface.

10. JavaScript ‘Back’ Button

This is another fairly simple and crude example, but not something to be overlooked. You can duplicate the browser’s back button in JavaScript with a simple value inside an HREF attribute. This will access the most recent website in your saved history and navigate back.

<a href="javascript:history.back(1)">Previous Page</a>

Source

11. Check Type of JS Object

This last function of code is great for debugging and generally handling response data. JavaScript has a number of different object types including strings, integers, arrays, and generic objects. If you are working with a large set of variables and need to pull data from a database then you may not know exactly what type of response you’re getting.

function objIs(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

objIs('String', 'test'); // true
objIs('String', new String('test')); // true

Source

Just copy over this function into your JavaScript and you can run this for any variable type. See the two examples at the bottom of the code snippet for checking against a new String variable.

Final Thoughts

You should feel free to copy any of these code snippets and save them for later use. There are plenty of designers who struggle with frontend scripting, and so I hope this collection may prove useful to even a few people. But advanced-to-intermediate level JavaScript developers could also find use in saving these codes to expedite projects in the future.

Jake is a creative writer and UI designer by trade. You can follow him on twitter @jakerocheleau or learn more at his personal website JakeRocheleau.com.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *