CSS Naming Conventions – Getting your HTML CSS and JavaScript to play nicely with one another.

Posted by Nick on Aug 19, 2010 in Development Tips and Tricks |

As web development becomes more complicated so does the need to organize our code in to something that is manageable. Gone are the days of

<a onclick=”function()”>.

Nowadays we are often binding event with JavaScript libraries like JQuery.

$(‘myFavDomElement’).click(function(){

alert(“helloWorld”);

});

This is great but carries some potential shortcomings.  One problem with this new style of code is that in highly front-end centric environments we have the potential to end up with thousands of lines of codes patched together between multiple JavaScript files ( *avoid http request whenever possible ).  In order to avoid confusion and avoid regression issues, I recommend breaking your CSS classes out in to two different areas:

  1. Those which control CSS layout and style.
  2. Those which are bound to your JavaScript.

Choose a naming convention that makes sense and works for you.  Recently I have been using the following patter within an MVC environment.

JavaScript Classes

  1. jg_myElement  – JavaScript Global Class, used for things like global header functionality.
  2. jv_myElement – JavaScript View Class, used for things like functionality that is relevant only to that view.
  3. jm_myElement – JavaScript Module Class,  used to control functionality on portable modules that can be used on multiple but not all pages.

CSS Classes

  1. cg_myElement  – CSS Global Class, used for things like global header layout and style.
  2. cv_myElement – CSS View Class, used for things like layout and style of page elements relevant only to that view.
  3. cm_myElement – CSS Module Class,  used for layout and styling of portable modules that can be used on multiple but not all pages.

Your new code should look something like this:

Ex: This is an example of a search button that may be used in multiple places on the web page.

<style type=”text/css”>

.cm_Search{margin:10px; padding:10px;border:1px solid #2F2F2F; background-color:#AFAFAF}

</style>

<script type=”text/javascript”>

$(document).ready(function() {

$(‘.jm_Search’).click(function(){

alert(“Hello World!”);

});

});

</script>

<div class=”jm_Search cm_Search”>

<p>Search</p>

</div>

As a developer I can now add/change/remove any cg_, cv_ and cm_ classes with no fear of interrupting JavaScript functionality.

Leave a Reply

XHTML: You can use these tags:' <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Copyright © 2010-2014 Nick Stark All rights reserved.

DUI Magic - Seattle DUI Attorney