Get found on the web

Quality Web Design for Small
to Medium Businesses in New Hampshire

Understanding MVVM – A Guide For JavaScript Developers

Posted on by Portsmouth Media in archives, Blog Leave a comment

An article I was reading about plugins

MVVM (Model View ViewModel) is an architectural pattern based on MVC and MVP, which attempts to more clearly separate the development of user-interfaces (UI) from that of the business logic and behaviour in an application. To this end, many implementations … href=”http://addyosmani.com/blog/understanding-mvvm-a-guide-for-javascript-developers/”>Continue reading class=”meta-nav”>→
AddyOsmani.com | Articles for developers


The Smashing Guide To Moving The Web Forward

Posted on by Portsmouth Media in Blog Leave a comment

An article I was reading about plugins

In this article I’d like to talk about how you can help give back to the Web and a new project that seeks to make this process easier: MoveTheWebForward.org. If you’ve ever thought about contributing to the community but weren’t … href=”http://addyosmani.com/blog/movingthewebforward/”>Continue reading class=”meta-nav”>→
AddyOsmani.com | Articles for developers


The Smashing Guide To Moving The Web Forward

Posted on by Portsmouth Media in Blog Leave a comment

An article I was reading about css3





 



 


Many of us rely on open source tools, technologies and standards to help improve the work we do on a daily basis. None of this would however be possible without the hard work, commitment and dedication that others, just like you, have invested in giving back to the Web community over the past two decades.

Modernizr, HTML5 Boilerplate and jQuery are just a few examples of well known projects which were born from a desire to put something out there that could help others on the Web do more. These projects evolved because developers started using them and thought, “Hey, I could do something to help make this better. I bet it could save someone else’s time if I shared this with the world.”

Web standards like CSS3, HTML5 and the foundations of the Web as we know them would also not have been possible without people (just like readers of this post) spending time researching use cases, writing proposals, implementing features and catering to existing and future requirements that could be used by everyone. When you think about it, both standards and open source projects have had a large hand to play in the Web as we know it today.

In this article I’d like to talk about how you can help give back to the Web and a new project that seeks to make this process easier: MoveTheWebForward.org. If you’ve ever thought about contributing to the community but weren’t sure just how, I hope this serves as a good starting point for your journey.

Why Help Move The Web Forward?

In most cases, developers and designers that contribute back do so because of an inherent passion or desire to either improve an open source project, Web standards or the quantity of educational material freely available online.

What you get back from this is (in my opinion) worth every minute of effort.

Contributing to open source projects, you can learn more about the intricacies of programming languages, libraries and standards implementations than you probably could if you were just been a passive user. This can help you gain a better appreciation for how the Web is built, but also improve the quality of the development work you do as a part of your job.

Whilst not the reason most people do it, open source involvement can also often lead to more fulfilling jobs (and occasionally more pay). Demonstrating you have passion (and skills) in a focused area can help highlight you to recruiters at companies where those skills are highly valued.

Finally, involvement can help improve your knowledge, whether it’s simply writing tutorials about standards for others, actually being involved in submitting patches or feature implementations to browser vendors and libraries or contributing to discussions in standards mailing lists (which I’ll discuss in greater detail shortly).

“For me, open source is not about giving back, but its more about being sociable with the developers you admire. I really like forming small groups to work on projects and challenges together, or just like-minded folks that chitchat and passively learn new skills regularly.

The community has given me back great friends and I think we’ve all found more ways to be fulfilled by the work we create.”

 —  Paul Irish, HTML5 Boilerplate, Modernizr, jQuery team

Contributing

1. What can you do and how much time can you contribute?
Before we look at what you can do to contribute back to the Web, ask yourself three very simple questions: What are your strongest skill-sets? How you might these be used in an open source project? How much time and effort would you like to contribute to giving back?

Understandably, a lot of us have full-time jobs and it can be tricky sometimes trying to fit in extra side-projects into our schedules. The great thing about the Web is that there’s never too little or too much time that you can spend moving it forward.

10 minutes is enough to help someone stuck on a Web-development problem and an hour here or there is enough to greatly improve existing open source projects. If you have the desire to give back, anything is possible.

2. Pick a project or Web standard/specification you would like to work on
Once you have some rough ideas of much time you can contribute, you’ll need to decide on the project, standards group or area you would like to help with. The good news is that there’s a great new initiative to help with this called MoveTheWebForward.org (MWF), driven by some of the talented people that brought us HTML5 Boilerplate.

MWF is a project that aims to make it easy for anyone to get started contributing to the open source community.

Whether you’re just diving into Web development, or are have been doing it back since tables were cool for layout, there are a number ways for you to give back to the community. MWF makes it easy to help anyone find ways to contribute back to the Web platform by giving you a list of ideas, resources and guides to get you started.

Not sure what projects to look at or where to find lazy-Web requests you can get done in an afternoon? Not a problem. The site breaks down almost all aspects of open source contribution and even separates things based on your level of experience. Regardless of whether you’re a CSS wizard, a JavaScript ninja, or a C++ hacker wanting to play with WebKit there’s something on MWF that everyone can help with.

Don’t see a project that applies to you on there yet? Don’t worry. It’s being updated everyday and other members of the community can submit pull requests to add new things to it. You may also find it helpful reviewing what libraries and technologies you regularly use personally, whether it be a CSS feature like psuedo-selectors or a JavaScript library like Modernizr or jQuery. Beyond the basics, you may have some insights or ideas for how these could be improved in some subtle way.

Do you feel the implementation of a particular feature isn’t quite as usable as it could be? Are there circumstances where a solution just doesn’t give developers everything they need? The learnings you’ve obtained whilst using things on a day to day basis are something you can share with a project to help improve it.

Take a look at MoveTheWebForward.org each week and if you’re up for it, consider committing to getting a small task done that can push the Web forward.

3. What would you like your role in the project to be?
Most open source projects (and standards groups) have a number of key areas that they require assistance with. In no chronological order these are:

  • Core development
  • Discussions / Mailing lists
  • Documentation
  • Bug submissions triage
  • Operations
  • Testing
  • Site & UI Design
  • Developer Evangelism
  • Support

Depending on the project there may also be areas such as ‘specification writing’ that are necessary in order for features to be discussed before they are implemented.

Core Development

Core development generally involves development of a core set of features, fixes or rewrites for JavaScript libraries, and browser feature implementations or patches when it comes to Web standards.

Whilst beginners won’t generally be directly discouraged from trying to get involved with core development, it’s more often intermediate and advanced users of libraries or features that are better equipped to optimally implement code that is efficient, performs well and passes unit tests.

“I love open source. I’ve been hooked on jQuery since John Resig accepted my first patch in January 2006. It’s been at the center of several profitable projects that I’ve built. Contributing to both jQuery’s code and documentation just seems like the right way to pay that forward.”

 —  Dave Methvin, jQuery team

If you’re interested in getting involved with core development, I suggest spending time familiarizing yourself with:

  • The build/setup instructions for the open source project you wish to contribute to
  • How the project is structured so you can later experiment with making patches and running tests
  • The project contribution guide. Most open source projects these days are hosted on GitHub. This means that filing patches is usually as straight-forward as filing a pull request, but make sure to follow the project’s guidelines on doing this. At jQuery, we require developers to file a ticket in our bug tracker to accompany pull requests but it’s a subtle step that we cover in the contribution guide.
  • Where current contributors congregate to discuss issues, features and patches — with Web standards or libraries this could be a mailing list or an IRC channel. Mozilla has dedicated channels for people wishing to contribute to the MDN as do jQuery and many, many other open source projects.

“Whether you’re contributing to existing projects or open-sourcing projects of your own, giving back to the community is a great way to learn about Cool New Stuff™.”

 —  Mathias Bynens. jsPerf, HTML5 Boilerplate

Discussions & Mailing Lists

Standards Mailing Lists

We all know that Web standards are important. They help ensure the code we write works across different technologies, for people of different abilities and most importantly across all browsers. If you have an interest in pushing the Web forward by getting involved with the standards process, there are a number of different mailing lists you can subscribe to (and participate in) should you have particularly strong feelings about the direction particular technologies or features should be taking.

These mailing lists include public-html, public-webapps, es-discuss, www-style, public-fx and WHATWG. I recommend spending time familiarizing yourself with how contributors to these lists approach discussion as you’ll want to ensure your posts are read rather than ignored – specifically, research proposals, read spec wikis where available and ask other posters for their input offline if you’re unsure about anything.

Note: Chapter 2 of Mark Pilgrim’s HTML5 book contain an excellent discussion of how standards get pushed through mailing lists. It also covers some of the evolution of standards through history and is a recommended read for those interested in grasping how the process works. You can read it for free online here: http://diveintohtml5.info/past.html

The jQuery Standards Team

While many of us would like to see change, the reality is due to time restrictions and lengthy formal processes we’re not always able to participate in standards discussions, get involved with writing specifications and contribute to meetings about the future of features. This can sometimes make it difficult for Web developers to have a voice.

Another problem is that for those that do get involved with the process, it can often feel like participating on a particular thread in standards mailing lists has a limited impact because the Web community is so fragmented. There’s also a lot of assumed knowledge required of existing discussions, decisions and historical context that can make it a little more challenging to get involved.

The jQuery project have set out to try changing this. They want you to have a voice in how the future of the Web is shaped which is why they created the jQuery Standards team. The standards team listens to suggestions or feedback you may have about current specs and if there’s sufficient interest in making changes related to your concerns, they’ll file tickets on your behalf in the appropriate format.

For more information see: https://github.com/jquery/standards

Code/Project Mailing Lists

Mailing lists for code projects (e.g jQuery, Dojo) tend to work quite similarly to those for Web standards. The only real differences are that discussions can sometimes be more fast-paced and generally target the resolution of features or fixes being targeted for a specific library rather than something as broad as a standard.

You don’t have to be someone that implements library code to be able to get involved with these discussions, but it does help having a good level of familiarity with both the library, alternatives to it and the general space being worked on. As per my early suggestion, spend a little time analyzing the best way to jump in with suggestions or ideas to increase the chances of having a positive impact on the conversation.

Documentation

When most developers think about getting involved with open source, their first thought is usually about writing code that can one day be used by many others.Whilst it’s true that implementations are of course important, documentation is an equally if not more important part of the release process.

Think about it: when you first learn about a new specification that’s been implemented or about some new framework that’s just been released, your first port of call is to look at the documentation or the getting started guide so you can figure out just how to use it. Without this documentation, most projects (and indeed, specs) would be nowhere near as popular or widely used as they are today.

The great thing about documentation is that (unlike full-blown patches or implementations), your contributions can be as small or as large as your time permits. I’ve seen developers contribute simple one line changes to documentation whilst others have provided the equivalent of complete chapters of written docs because they wanted to make it easier for others to understand how everything works. If you’re good at writing, consider giving docs a try.

Writing docs is also a great way to increase your knowledge about how to use the software or tool you’re writing it for. If you feel comfortable using a particular project, consider looking at the bugs files on their trackers. This can offer insight into what confuses users and you can try writing out documentation for such workflows or actions that are unclear.

The barrier of entry is a little lower than core development and there are many well known open source projects that could use your help in this area.

Bug Triage (Issue Moderation)

Most open source projects (including frameworks like Modernizr and browsers such as WebKit) have their own issue or bug trackers. These are typically used as a central location where users can submit issues, feature requests and track the progress of what’s currently being addressed. As projects become more widely used, the number of issues received incrementally grows and there becomes a need for these issues to be moderated. Reasons issues may need to be moderated include being:

  • Invalid
    In many cases, users will simply submit issues with a project or specification without spending enough time debugging their solution. Sorting the invalid tickets from the valid ones makes it easier for core developers to focus on addressing the important ones.
  • Duplicates
    The issue may have been previously submitted. This is easy to discover as the majority of trackers have their own search options.
  • Patch welcome
    Where an issue is acknowledged but is beyond the scope (or time-constraints) of a project to patch itself.
  • Won’t or Can’t fix
    There are issues users may submit which a project may admit is a valid problem, but which may not be currently possible to fix, either due to the direction the project is taking or the broader implications it may have on a codebase.

Moderators are usually required to help narrow down issues to a list of (valid) confirmed issues and feature requests. The great thing about being involved in bug triage is that you’re regularly required to evaluate code samples and establish why a bug may or may not in fact be, valid.

“Contributing to the development of open source software, such as jQuery and Popcorn.js, is my way of ensuring that the future is awesome – in both the things people create and the tools that they’ll use to create them.”

 —  Rick Waldron. jQuery team, Popcorn.js

You’ll often find yourself writing short solutions that address the problem as a workaround and the knowledge you build up from these can greatly help avoid the same problems if you run into them in other projects or at work.

Operations

Larger open source projects often have to deal with millions of requests for downloading their library every single day. Even when offering a CDN-hosted version (like we do at jQuery), they still have a large quantity of requests coming in to access their sites, documentation pages and official tutorials. None of these would be able to cope under strain without the hard work that experienced ops people have to offer.

“Being involved in operations has not only given me the opportunity to contribute and sharpen my skills with git, writing tests and streamlining processes, it’s also allowed me to meet some incredibly talented people and make fantastic friends. Contributing to open source has made me better. Period.”

 —  Dan Heberden, jQuery team

Operations (ops) also take care of some of the smaller day to day tasks like granting permissions for new contributors wishing to access different parts of a site, setting up scripts to help automate and streamline tasks and generally ensuring the visible public face of a project stays online. If you have strong ops skills, feel free to reach out to projects (both small and large) as they likely wouldn’t mind some more assistance, either now or at some point in the future.

Testing

Implementations of new browser and library features require an extensive amount of testing prior to being released. This covers everything from ensuring 100% unit test coverage is reached, tests are written (or provided) for any patches submitted and where applicable, tests are run across all browsers, environments and devices your particular project targets. If you’re a stiffler for ensuring code is stable prior to being pushed to end-users, you may be interested in helping out with testing efforts. Speak to current contributors to the project to find out their current need for members looking specifically at this area.

Site & UI Design

Did you know that at projects like HTML5 Boilerplate and jQuery, there are dedicated designers that just focus on ensuring site layouts and UI components look at best as possible in every browser? Every open source site or group, from the W3C to JavaScript libraries generally have front-facing websites and it’s often the case that if a redesign or site maintenance isn’t already in the pipe-line, they could use your help.

“Working on open source projects means you have the skills of several people to tap on. It is a great place to learn Web development, creating workflows that work for collaboration. Moreover, it’s safe – it’s not like you’ll get fired for testing things out. The projects I contribute to are directed towards problems I struggled with myself and wish other designers had.”

 —  Divya Manian, HTML5 Boilerplate

Before you approach a project about helping them with any design work, talk to the members to see what their plans are or what they’d ideally like someone to work on. They may ask you to present a mockup of concepts you may have to establish if they’d like to get you involved with their current design team or in taking on your ideas for one of their next versions. A good to strong knowledge of HTML/CSS and a little JavaScript is always useful to have, but even if you just design in Photoshop that’s another piece of work someone else in the community could take further.

Evangelism & Support

The role of technical evangelists varies quite a lot in open source projects. Its goals can include:

  • Supporting developers in the community by providing assistance, answering questions and making it as easy as possible for developers to solve problems they may be running into (doing so via IRC, Twitter or forums is quite common).
  • Working with developers in the community to help understand why particular standards, browsers, libraries or tools should be used and can make developer’s lives easier.
  • Writing tutorials, creating screencasts and building demos that help educate others.
  • Generally speaking on behalf of the project at events to further enhance awareness about the project’s goals and offerings.
  • If you enjoy helping people solve problems or have a passion for writing (but aren’t a big fan of writing documentation), consider giving evangelism a try.

Share Knowledge, Share Experiences and Build New Things

Beyond assisting with the goals of a specific code project or standards working group, there’s a an array of other useful things you could be doing to help push the Web forward.

Building
Many of the most popular open source projects today once started out as tools and workarounds that a developer or designer worked on to satisfy a personal need. If you love hacking on code, please consider sticking your work up on GitHub and sharing it with the rest of the world. There may be many others (just like you) that your work could end up helping or inspiring it’s a great feeling knowing that you’ve saved someone else from dealing with the same headaches you once had to yourself.

Note: GitHub offer a regular free class on the ‘basics’ that you can sign up for. You can also get a free copy of ‘Pro Git’ that covers most of the fundamentals.

Blogging
Although I’m involved in open source projects, my biggest contribution to the Web is still in my day to day technical writing. Teaching through this medium is a great learning tool and you’ll often find yourself learning more as you write and research about the topics you’re conveying.

Remember that your words can be a very powerful tool for pushing education on the Web forward. For this reason I encourage you to consider writing about what you do and learn — write tutorials, create demos, post gists, write essays.

“After being repeatedly nudged by people to start writing about changes to WebKit and Chromium, which I had been monitoring for a long time already, I wrote my first article back in August 2010.

To date, 64 articles have been published and many more people are aware of and get involved in the implementation of cutting-edge features at both projects. I myself am now part of the Google Chrome and WebKit teams, focusing on improving both the browser as the Web, doing that which I love to do.”

 —  Peter Beverloo, Google Chrome team

Don’t be afraid to make mistakes (because that’s how we all improve). It’s absolutely okay for you to not be a complete expert or authority on a topic. Share what you do know because it has the potential to help many other developers and designers out there. Reach out to others in the community if you don’t know something — ask questions and prompt conversations.

Contribute to the MDN
For those interested in getting involved with writing, it’s okay if you don’t have your own blog. Almost any designer or developer with HTML, CSS or JavaScript skills can also contribute back to the Web through the MDN (Mozilla Developer Network).

The Mozilla Developer Network, also known as MDN.

The MDN is a community of developers building resources to improve the Web, regardless of what browser or platform you’re using. Anyone can contribute to it as the entire site is a wiki (just like Wikipedia). There are sections that detail specs, pages that are just tutorials and others that are just guides to quirks that are useful to be aware of when using particular browser features.

“When I learned about Web standards not much was available out there. The Mozilla Developer Network was one of the first resources I kept going back to when I was stuck. The reason why it still is that way is that it is a living resource that anyone is invited to edit and keep clean.

It is pretty rewarding to be part of this and knowing that what you put on the Web is part of something that by definition is there to keep the Web free, open, and make it easier for the next generation of Web makers not to have to make the same mistakes we did to build something good for the Web.”

 —  Christian Heillman, Mozilla

To give you an example, here’s a page I fleshed out during one of the MDN sprints with (reliable) links to get started with learning Web development: Introduction to Web development. Simple, right? It’s nothing more than an organized page of links, but prior to the new learning section on the MDN site being launched, it helped developers and designers get started with basic fundamentals when they were unsure where to look.

Mozilla evangelists regularly hang out in #mdn on irc.mozilla.org (IRC) and are always happy to help new contributors get started if you have any questions. Consider giving it a try!

Conclusion

That’s it for this guide. I’ll be sure to update it if there’s anything I’ve missed out on, but I hope it inspires others to consider giving back to the Web platform. Remember to check out MoveTheWebForward.org if you’re interested in picking a task you can start working on today. Together, we can help move the Web forward.

Further Reading

With special thanks to Divya Manian, Nicolas Gallagher and Paul Irish. Images courtesy of the 56 Geeks project.

(vf) (il)


© Addy Osmani for Smashing Magazine, 2011.

Smashing Magazine Feed


The Developer’s Guide To Conflict-Free JavaScript And CSS In WordPress

Posted on by Portsmouth Media in Blog Leave a comment

An article I was reading about css3





 



 


sm-wp-css-js

Imagine you’re playing the latest hash-tag game on Twitter when you see this friendly tweet:

You might want to check your #WP site. It includes two copies of jQuery. Nothing’s broken, but loading time will be slower.

You check your source code, and sure enough you see this:

<script src="/wp-includes/js/jquery/jquery.js?ver=1.6.1" type="text/javascript"></script>
<script src="/wp-content/plugins/some-plugin/jquery.js"></script>

What Went Wrong?

The first copy of jQuery is included the WordPress way, while some-plugin includes jQuery as you would on a static HTML page.

A number of JavaScript frameworks are included in WordPress by default, including:

  • Scriptaculous,
  • jQuery (running in noConflict mode),
  • the jQuery UI core and selected widgets,
  • Prototype.

A complete list can be found in the Codex. On the same page are instructions for using jQuery in noConflict mode.

Avoiding the Problem

WordPress includes these libraries so that plugin and theme authors can avoid this problem by using the wp_register_script and wp_enqueue_script PHP functions to include JavaScript in the HTML.

Registering a file alone doesn’t do anything to the output of your HTML; it only adds the file to WordPress’s list of known scripts. As you’ll see in the next section, we register files early on in a theme or plugin where we can keep track of versioning information.

To output the file to the HTML, you need to enqueue the file. Once you’ve done this, WordPress will add the required script tag to the header or footer of the outputted page. More details are provided later in this article.

Registering a file requires more complex code than enqueueing the files; so, quickly parsing the file is harder when you’re reviewing your code. Enqueueing the file is far simpler, and you can easily parse how the HTML is being affected.

For these techniques to work, the theme’s header.php file must include the line <?php wp_head(); ?> just before the </head> tag, and the footer.php file must include the line <?php wp_footer(); ?> just before the </body> tag.

Registering JavaScript

Before registering your JavaScript, you’ll need to decide on a few additional items:

  • the file’s handle (i.e. the name by which WordPress will know the file);
  • other scripts that the file depends on (jQuery, for example);
  • the version number (optional);
  • where the file will appear in the HTML (the header or footer).

This article refers to building a theme, but the tips apply equally to building a plugin.

Examples

We’ll use two JavaScript files to illustrate the power of the functions:

The first is base.js, which is a toolkit of functions used in our example website.

function makeRed(selector){
  var $ = jQuery; //enable $ alias within this scope
  $(function(){
    $(selector).css('color','red');
  });
}

The base.js file relies on jQuery, so jQuery can be considered a dependency.

This is the first version of the file, version 1.0.0, and there is no reason to run this file in the HTML header.

The second file, custom.js, is used to add the JavaScript goodness to our website.

makeRed('*');

This custom.js file calls a function in base.js, so base.js is a dependency.

Like base.js, custom.js is version 1.0.0 and can be run in the HTML footer.

The custom.js file also indirectly relies on jQuery. But in this case, base.js could be edited to be self-contained or to rely on another framework. There is no need for jQuery to be listed as a dependency of custom.js.

It’s now simply a matter of registering your JavaScript using the function wp_register_script. This takes the following arguments:

  • $handle
    A string
  • $source
    A string
  • $dependancies
    An array (optional)
  • $version
    A string (optional)
  • $in_footer
    True/false (optional, default is false)

When registering scripts, it is best to use the init hook and to register them all at once.

To register the scripts in our example, add the following to the theme’s functions.php file:

function mytheme_register_scripts() {
  //base.js – dependent on jQuery
  wp_register_script(
    'theme-base', //handle
    '/wp-content/themes/my-theme/base.js', //source
    array('jquery'), //dependencies
    '1.0.0', //version
    true //run in footer
  ); 

  //custom.js – dependent on base.js
  wp_register_script(
    'theme-custom',
    '/wp-content/themes/my-theme/custom.js',
    array('theme-base'),
    '1.0.0',
    true
  );
}
add_action('init', 'mytheme_register_scripts');

There is no need to register jQuery, because WordPress already has. Re-registering it could lead to problems.

You Have Achieved Nothing!

All of this registering JavaScript files the WordPress way has, so far, achieved nothing. Nothing will be outputted to your HTML files.

To get WordPress to output the relevant HTML, we need to enqueue our files. Unlike the relatively long-winded commands required to register the functions, this is a very simple process.

Outputting the JavaScript HTML

Adding the <script> tags to your HTML is done with the wp_enqueue_script function. Once a script is registered, it takes one argument, the file’s handle.

Adding JavaScript to the HTML is done in the wp_print_scripts hook with the following code:

function mytheme_enqueue_scripts(){
  if (!is_admin()):
    wp_enqueue_script('theme-custom'); //custom.js
  endif; //!is_admin
}
add_action('wp_print_scripts', 'mytheme_enqueue_scripts');

Of our two registered JavaScript files (base.js and custom.js), only the second adds JavaScript functionality to the website. Without the second file, there is no need to add the first.

Having enqueued custom.js for output to the HTML, WordPress will figure out that it depends on base.js being present and that base.js, in turn, requires jQuery. The resulting HTML is:

<script src="/wp-includes/js/jquery/jquery.js?ver=1.6.1" type="text/javascript"></script>
<script src="/wp-content/themes/my-theme/base.js?ver=1.0.0" type="text/javascript"></script>
<script src="/wp-content/themes/my-theme/custom.js?ver=1.0.0" type="text/javascript"></script>

Registering Style Sheets

Both of the functions for adding JavaScript to our HTML have sister PHP functions for adding style sheets to the HTML: wp_register_style and wp_enqueue_style.

As with the JavaScript example, we’ll use a couple of CSS files throughout this article, employing the mobile-first methodology for responsive Web design.

The mobile.css file is the CSS for building the mobile version of the website. It has no dependencies.

The desktop.css file is the CSS that is loaded for desktop devices only. The desktop version builds on the mobile version, so mobile.css is a dependency.

Once you’ve decided on version numbers, dependencies and media types, it’s time to register your style sheets using the wp_register_style function. This function takes the following arguments:

  • $handle
    A string
  • $source
    A string
  • $dependancies
    An array (optional, default is none)
  • $version
    A string (optional, the default is the current WordPress version number)
  • $media_type
    A string (optional, the default is all)

Again, registering your style sheets using the init action is best.

To your theme’s functions.php, you would add this:

function mytheme_register_styles(){
  //mobile.css for all devices
  wp_register_style(
    'theme-mobile', //handle
    '/wp-content/themes/my-theme/mobile.css', //source
    null, //no dependencies
    '1.0.0' //version
  ); 

  //desktop.css for big-screen browsers
  wp_register_style(
    'theme-desktop',
    '/wp-content/themes/my-theme/desktop.css',
    array('theme-mobile'),
    '1.0.0',
    'only screen and (min-width : 960px)' //media type
  ); 

  /* *keep reading* */
}
add_action('init', 'mytheme_register_styles');

We have used CSS3 media queries to prevent mobile browsers from parsing our desktop style sheet. But Internet Explorer versions 8 and below do not understand CSS3 media queries and so will not parse the desktop CSS either.

IE8 is only two years old, so we should support its users with conditional comments.

Conditional Comments

When registering CSS using the register and enqueue functions, conditional comments are a little more complex. WordPress uses the object $wp_styles to store registered style sheets.

To wrap your file in conditional comments, add extra information to this object.

For Internet Explorer 8 and below, excluding mobile IE, we need to register another copy of our desktop style sheet (using the media type all) and wrap it in conditional comments.

In the code sample above, /* *keep reading* */ would be replaced with the following:

global $wp_styles;
wp_register_style(
  'theme-desktop-ie',
  '/wp-content/themes/my-theme/desktop.css',
  array('theme-mobile'),
  '1.0.0'
); 

$wp_styles->add_data(
  'theme-desktop-ie', //handle
  'conditional',  //is a conditional comment
  '!(IEMobile)&(lte IE 8)' //the conditional comment
);

Unfortunately, there is no equivalent for wrapping JavaScript files in conditional comments, presumably due to the concatenation of JavaScript in the admin section.

If you need to wrap a JavaScript file in conditional comments, you will need to add it to header.php or footer.php in the theme. Alternatively, you could use the wp_head or wp_footer hooks.

Outputting The Style Sheet HTML

Outputting the style sheet HTML is very similar to outputting the JavaScript HTML. We use the enqueue function and run it on the wp_print_styles hook.

In our example, we could get away with telling WordPress to queue only the style sheets that have the handles theme-desktop and theme-desktop-ie. WordPress would then output the mobile/all media version.

However, both style sheets apply styles to the website beyond a basic reset: mobile.css builds the website for mobile phones, and desktop.css builds on top of that. If it does something and I’ve registered it, then I should enqueue it. It helps to keep track of what’s going on.

Here is the code to output the CSS to the HTML:

function mytheme_enqueue_styles(){
  if (!is_admin()):
    wp_enqueue_style('theme-mobile'); //mobile.css
    wp_enqueue_style('theme-desktop'); //desktop.css
    wp_enqueue_style('theme-desktop-ie'); //desktop.css lte ie8
  endif; //!is_admin
}
add_action('wp_print_styles', 'mytheme_enqueue_styles');

What’s The Point?

You may be wondering what the point is of going through all of this extra effort when we could just output our JavaScript and style sheets in the theme’s header.php or using the wp_head hook.

In the case of CSS in a standalone theme, it’s a valid point. It’s extra work without much of a payoff.

But with JavaScript, it helps to prevent clashes between plugins and themes when each uses a different version of a JavaScript framework. It also makes page-loading times as fast as possible by avoiding file duplication.

WordPress Frameworks

This group of functions can be most helpful when using a framework for theming. In my agency, Soupgiant, we’ve built a framework to speed up our production of websites.

As with most agencies, we have internal conventions for naming JavaScript and CSS files.

When we create a bespoke WordPress theme for a client, we develop it as a child theme of our framework. In the framework itself, we register a number of JavaScript and CSS files in accordance with our naming convention.

In the child theme, we then simply enqueue files to output the HTML.

function clienttheme_enqueue_css() {
  if (!is_admin()):
    wp_enqueue_style('theme-mobile');
    wp_enqueue_style('theme-desktop');
    wp_enqueue_style('theme-desktop-ie');
  endif; //!is_admin
}
add_action('wp_print_styles', 'clienttheme_enqueue_css'); 

function clienttheme_enqueue_js() {
  if (!is_admin()):
    wp_enqueue_script('theme-custom');
  endif; //!is_admin
}
add_action('wp_print_scripts', 'clienttheme_enqueue_js');

Adding CSS and JavaScript to our themes the WordPress way enables us to keep track of exactly what’s going on at a glance.

A Slight Limitation

If you use a JavaScript framework in your theme or plugin, then you’re stuck with the version that ships with the current version of WordPress, which sometimes falls a version or two behind the latest official release of the framework. (Upgrading to a newer version of the framework is technically possible, but this could cause problems with other themes or plugins that expect the version that ships with WordPress, so I’ve omitted this information from this article.)

While this prevents you from using any new features of the framework that were added after the version included in WordPress, the advantage is that all theme and plugin authors know which version of the framework to expect.

A Single Point Of Registration

Register your styles and scripts in a single block of code, so that when you update a file, you will be able to go back and update the version number easily.

If you use different code in different parts of the website, you can wrap the logic around the enqueue scripts.

If, say, your archive pages use different JavaScript than the rest of the website, then you might register three files:

  • base JavaScript (registered as theme-base),
  • archive JavaScript (registered as theme-archive),
  • general JavaScript (registered as theme-general).

Again, the base JavaScript adds nothing to the website. Rather, it is a group of default functions that the other two files rely on. You could then enqueue the files using the following code:

function mytheme_enqueue_js(){
  if (is_archive()) {
    wp_enqueue_script('theme-archive');
  }
  elseif (!is_admin()) {
    wp_enqueue_script('theme-general');
  }
}
add_action('wp_print_scripts', 'mytheme_enqueue_js');

Using The Google AJAX CDN

While using JavaScript the WordPress way will save you the problem of common libraries conflicting with each other, you might prefer to serve these libraries from Google’s server rather than your own.

Using Jason Penny’s Use Google Libraries plugin is the easiest way to do this. The plugin automatically keeps jQuery in noConflict mode.

Putting It All Together

Once you’ve started registering and outputting your scripts and styles the WordPress way, you will find that managing these files becomes a series of logical steps:

  1. Registration to manage:
    • version numbers,
    • file dependencies,
    • media types for CSS,
    • code placement for JavaScript (header or footer);
  2. Enqueue/output files to HTML:
    • logic targeting output to specific WordPress pages,
    • WordPress automating dependencies.

Eliminating potential JavaScript conflicts from your WordPress theme or plugin frees you to get on with more important things, such as following up on sales leads or getting back to that hash-tag game that was so rudely interrupted.

(al)


© Peter Wilson for Smashing Magazine, 2011.

Smashing Magazine Feed


WordPress Essentials: The Definitive Guide To WordPress Hooks

Posted on by Portsmouth Media in Blog Leave a comment

An article I was reading about css3





 



 


If you’re into WordPress development, you can’t ignore hooks for long before you have to delve into them head on. Modifying WordPress core files is a big no-no, so whenever you want to change existing functionality or create new functionality, you will have to turn to hooks.

wp-hooks-guide

In this article, I would like to dispel some of the confusion around hooks, because not only are they the way to code in WordPress, but they also teach us a great design pattern for development in general. Explaining this in depth will take a bit of time, but bear with me: by the end, you’ll be able to jumble hooks around like a pro.

Why Hooks Exist

I think the most important step in grasping hooks is to understand the need for them. Let’s create a version of a WordPress function that already exists, and then evolve it a bit using the “hooks mindset.”

   function get_excerpt($text, $length = 150) {
      $excerpt = substr($text,$length)
      return $excerpt;
   }

This function takes two parameters: a string and the length at which we want to cut it. What happens if the user wants a 200-character excerpt instead of a 150-character one? They just modify the parameter when they use the function. No problem there.

If you use this function a lot, you will notice that the parameter for the text is usually the post’s content, and that you usually use 200 characters instead of the default 150. Wouldn’t it be nice if you could set up new defaults, so that you didn’t have to add the same parameters over and over again? Also, what happens if you want to add some more custom text to the end of the excerpt?

These are the kinds of problems that hooks solve. Let’s take a quick look at how.

   function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length", $length);

      $excerpt = substr($text,$length)
      return $excerpt;
   }

As you can see, the default excerpt length is still 150, but we’ve also applied some filters to it. A filter allows you to write a function that modifies the value of something — in this case, the excerpt’s length. The name (or tag) of this filter is excerpt_length, and if no functions are attached to it, then its value will remain 150. Let’s see how we can now use this to modify the default value.

   function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length");

      $excerpt = substr($text,$length)
      return $excerpt;
   }

   function modify_excerpt_length() {
      return 200;
   }

   add_filter("excerpt_length", "modify_excerpt_length");

First, we have defined a function that does nothing but return a number. At this point, nothing is using the function, so let’s tell WordPress that we want to hook this into the excerpt_length filter.

We’ve successfully changed the default excerpt length in WordPress, without touching the original function and without even having to write a custom excerpt function. This will be extremely useful, because if you always want excerpts that are 200 characters long, just add this as a filter and then you won’t have to specify it every time.

Suppose you want to tack on some more text, like “Read on,” to the end of the excerpt. We could modify our original function to work with a hook and then tie a function to that hook, like so:

   function get_excerpt($text, $length = 150) {

      $length = apply_filters("excerpt_length");

      $excerpt = substr($text,$length)
      return apply_filters("excerpt_content", $excerpt);
   }

   function modify_excerpt_content($excerpt) {
      return $excerpt . "Read on…";
   }
   add_filter("excerpt_content", "modify_excerpt_content");

This hook is placed at the end of the function and allows us to modify its end result. This time, we’ve also passed the output that the function would normally produce as a parameter to our hook. The function that we tie to this hook will receive this parameter.

All we are doing in our function is taking the original contents of $excerpt and appending our “Read on” text to the end. But if we choose, we could also return the text “Click the title to read this article,” which would replace the whole excerpt.

While our example is a bit redundant, since WordPress already has a better function, hopefully you’ve gotten to grips with the thinking behind hooks. Let’s look more in depth at what goes on with filters, actions, priorities, arguments and the other yummy options available.

Filters And Actions

Filters and actions are two types of hooks. As you saw in the previous section, a filter modifies the value of something. An action, rather than modifying something, calls another function to run beside it.

A commonly used action hook is wp_head. Let’s see how this works. You may have noticed a function at the bottom of your website’s head section named wp_head(). Diving into the code of this function, you can see that it contains a call to do_action(). This is similar to apply_filters(); it means to run all of the functions that are tied to the wp_head tag.

Let’s put a copyright meta tag on top of each post’s page to test how this works.

   add_action("wp_head", "my_copyright_meta");

   function my_copyright_meta() {
      if(is_singular()){
         echo "";
      }
   }

The Workflow Of Using Hooks

While hooks are better documented nowadays, they have been neglected a bit until recently, understandably so. You can find some good pointers in the Codex, but the best thing to use is Adam Brown’s hook reference, and/or look at the source code.

Say you want to add functionality to your blog that notifies authors when their work is published. To do this, you would need to do something when a post is published. So, let’s try to find a hook related to publishing.

Can we tell whether we need an action or a filter? Sure we can! When a post is published, do we want to modify its data or do a completely separate action? The answer is the latter, so we’ll need an action. Let’s go to the action reference on Adam Brown’s website, and search for “Publish.”

The first thing you’ll find is app_publish_post. Sounds good; let’s click on it. The details page doesn’t give us a lot of info (sometimes it does), so click on the “View hook in source” link next to your version of WordPress (preferably the most recent version) in the table. This website shows only a snippet of the file, and unfortunately the beginning of the documentation is cut off, so it’s difficult to tell if this is what we need. Click on “View complete file in SVN” to go to the complete file so that we can search for our hook.

In the file I am viewing, the hook can be found in the _publish_post_hook() function, which — according to the documentation above it — is a “hook to schedule pings and enclosures when a post is published,” so this is not really what we need.

With some more research in the action list, you’ll find the publish_post hook, and this is what we need. The first thing to do is write the function that sends your email. This function will receive the post’s ID as an argument, so you can use that to pull some information into the email. The second task is to hook this function into the action. Look at the finished code below for the details.

   function authorNotification($post_id) {
      global $wpdb;
      $post = get_post($post_id);
      $author = get_userdata($post->post_author);

      $message = "
         Hi ".$author->display_name.",
         Your post, ".$post->post_title." has just been published. Well done!
      ";
      wp_mail($author->user_email, "Your article is online", $message);
   }
   add_action('publish_post', 'authorNotification');

Notice that the function we wrote is usable in its own right. It has a very specific function, but it isn’t only usable together with hooks; you could use it in your code any time. In case you’re wondering, wp_mail() is an awesome mailer function — have a look at the WordPress Codex for more information.

This process might seem a bit complicated at first, and, to be totally honest, it does require browsing a bit of documentation and source code at first, but as you become more comfortable with this system, your time spent researching what to use and when to use it will be reduced to nearly nothing.

Priorities

The third parameter when adding your actions and filters is the priority. This basically designates the order in which attached hooks should run. We haven’t covered this so far, but attaching multiple functions to a hook is, of course, possible. If you want an email to be sent to an author when their post is published and to also automatically tweet the post, these would be written in two separate functions, each tied to the same tag (publish_post).

Priorities designate which hooked function should run first. The default value is 10, but this can be changed as needed. Priorities usually don’t make a huge difference, though. Whether the email is sent to the author before the article is tweeted or vice versa won’t make a huge difference.

In rarer cases, assigning a priority could be important. You might want to overwrite the actions of other plugins (be careful, in this case), or you might want to enforce a specific order. I recently had to overwrite functionality when I was asked to optimize a website. The website had three to four plugins, with about nine JavaScript files in total. Instead of disabling these plugins, I made my own plugin that overwrote some of the JavaScript-outputting functionality of those plugins. My plugin then added the minified JavaScript code in one file. This way, if my plugin was deactivated, all of the other plugins would work as expected.

Specifying Arguments

The fourth argument when adding filters and actions specifies how many arguments the hooked function takes. This is usually dictated by the hook itself, and you will need to look at the source to find this information.

As you know from before, your functions are run when they are called by apply_filters() or do_action(). These functions will have the tag as their first argument (i.e. the name of the hook you are plugging into) and then passed arguments as subsequent arguments.

For example, the filter default_excerpt receives two parameters, as seen in includes/post.php.

   $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );

The arguments are well named — $post_excerpt and $post — so it’s easy to guess that the first is the excerpt text and the second is the post’s object. If you are unsure, it is usually easiest either to look further up in the source or to output them using a test function (make sure you aren’t in a production environment).

   function my_filter_test($post_excerpt, $post) {
      echo "<pre>";
         print_r($post_excerpt);
         print_r($post);
      echo "</pre>";
   }
   add_filter("default_excerpt", "my_filter_test");

Variable Hook Names

Remember when we looked at the publish_post action? In fact, this is not used anymore; it was renamed in version 2.3 to {$new_status}_{$post->post_type}. With the advent of custom post types, it was important to make the system flexible enough for them. This new hook now takes an arbitrary status and post type (they must exist for it to work, obviously).

As a result, publish_post is the correct tag to use, but in reality, you will be using {$new_status}_{$post->post_type}. A few of these are around; the naming usually suggests what you will need to name the action.

Who Is Hooked On Who?

To find out which function hooks into what, you can use the neat script below, courtesy of WP Recipes. Use this function without arguments to get a massive list of everything, or add a tag to get functions that are hooked to that one tag. This is a great one to keep in your debugging tool belt!

function list_hooked_functions($tag=false){
 global $wp_filter;
 if ($tag) {
  $hook[$tag]=$wp_filter[$tag];
  if (!is_array($hook[$tag])) {
  trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
  return;
  }
 }
 else {
  $hook=$wp_filter;
  ksort($hook);
 }
 echo '<pre>';
 foreach($hook as $tag => $priority){
  echo "<br /><strong>$tag</strong><br />";
  ksort($priority);
  foreach($priority as $priority => $function){
  echo $priority;
  foreach($function as $name => $properties) echo "\t$name<br />";
  }
 }
 echo '</pre>';
 return;
}

Creating Your Own Hooks

A ton of hooks are built into WordPress, but nothing is stopping you from creating your own using the functions we’ve looked at so far. This may be beneficial if you are building a complex plugin intended for wide release; it will make your and other developers’ jobs a lot easier!

In the example below, I have assumed we are building functionality for users to post short blurbs on your website’s wall. We’ll write a function to check for profanity and hook it to the function that adds the blurbs to the wall.

Look at the full code below. The explanation ensues.

   function post_blurb($user_id, $text) {

      $text = apply_filters("blurb_text", $text);

      if(!empty($text)) {
         $wpdb->insert('my_wall', array("user_id" => $user_id, "date" => date("Y-m-d H:i:s"), "text" => $text), array("%d", %s", "%s"));
      }
   }

   function profanity_filter($text) {
      $text_elements = explode(" ", $text);
      $profanity = array("badword", "naughtyword", "inappropriatelanguage");

      if(array_intersect($profanity, $text_elements)) {
         return false;
      }
      else {
         return $text;
      }
   }

   add_filter("blurb_text", "profanity_filter");

The first thing in the code is the designation of the function that adds the blurb. Notice that I included the apply_filters() function, which we will use to add our profanity check.

Next up is our profanity-checking function. This checks the text as its argument against an array of known naughty words. By using array_intersect(), we look for array elements that are in both arrays — these would be the profane words. If there are any, then return false; otherwise, return the original text.

The last part actually hooks this function into our blurb-adding script.

Now other developers can hook their own functions into our script. They could build a spam filter or a better profanity filter. All they would need to do is hook it in.

Mixing And Matching

The beauty of this system is that it uses functions for everything. If you want, you can use the same profanity filter for other purposes, even outside of WordPress, because it is just a simple function. Already have a profanity-filter function? Copy and paste it in; all you’ll need to do is add the one line that actually hooks it in. This makes functions easily reusable in various situations, giving you more flexibility and saving you some time as well.

That’s All

Hopefully, you now fully understand how the hooks system works in WordPress. It contains an important pattern that many of us could use even outside of WordPress.

This is one aspect of WordPress that does take some time getting used to if you’re coming to it without any previous knowledge. The biggest problem is usually that people get lost in all of the filters available or in finding their arguments and so on, but with some patience this can be overcome easily. Just start using them, and you’ll be a master in no time!

(al)


© Daniel Pataki for Smashing Magazine, 2011.

Smashing Magazine Feed


The Developer’s Guide To Writing Cross-Browser JavaScript Polyfills

Posted on by Portsmouth Media in Blog Leave a comment

An article I was reading about plugins

I believe it is our responsibility as designers and developers to both advocate for best practices and encourage others to make the leap to using modern features for a modern web. At the same time, we need to do our best to avoid leaving users with older browsers behind. Polyfills – a term coined by [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community


Joomla! 1.6: A User’s Guide: Building a Successful Joomla! Powered Website

Posted on by Portsmouth Media in Blog Leave a comment

Joomla! 1.6: A User’s Guide: Building a Successful Joomla! Powered Website

This is the eBook version of the printed book.The Best Easy-to-Use Guide to Joomla!TM–The World’s #1 Open Source Content Management System   If you want to build sophisticated websites that can be easily edited and updated, you need to master Joomla. Now there’s an easy-to-read, easy-to-use guide to Joomla for every site manager, administrator, and developer. Leading Joomla consultant Barrie North covers all you need to get results: installation, administration, site organization, template

Rating: (out of reviews)

List Price: $ 35.99

Price:


Dreamweaver MX: A Beginner’s Guide, Ray West, Tom Muck,

Posted on by Portsmouth Media in Blog Leave a comment

Some recent dreamweaver auctions on eBay:


Beginner’s guide to planning, building & managing a web site or store

Posted on by Portsmouth Media in Blog Leave a comment

A few creative web ideas products I can recommend:

Beginner’s guide to planning, building & managing a web site or store
Your complete beginner’s guide to planning, designing, building, managing and promoting a business web site or store – written in plain English by accomplished online marketing professionals for SMEs & beginning Internet entrepreneurs
Beginner’s guide to planning, building & managing a web site or store

The 2012 Companion: A Creative Guide to Personal and Planetary Change
The 2012 Companion is the definitive guide filled with groundbreaking techniques to jump-start your spiritual ascension and cope with the 2012 shift. Hidden spiritual realms are revealed in 3 eBooks and 4 audiobooks by noted 2012 expert Carolyn Cobelo.
The 2012 Companion: A Creative Guide to Personal and Planetary Change


Web Style Guide, 3rd edition: Basic Design Principles for Creating Web Sites (Web Style Guide: Basic Design Principles for Creating Web Sites)

Posted on by Portsmouth Media in Blog Leave a comment

Web Style Guide, 3rd edition: Basic Design Principles for Creating Web Sites (Web Style Guide: Basic Design Principles for Creating Web Sites)

  • ISBN13: 9780300137378
  • Condition: New
  • Notes: BRAND NEW FROM PUBLISHER! BUY WITH CONFIDENCE, Over one million books sold! 98% Positive feedback. Compare our books, prices and service to the competition. 100% Satisfaction Guaranteed

Consistently praised in earlier editions as the best volume on classic elements of web site design, Web Style Guide, now in its Third Edition, continues its tradition of emphasis on fundamentals. Focusing on the needs of web site designers in corporations, government, nonprofit organizations, and academic institutions, the book explains established design principles and how they apply in web design projects in which information design, interface design, and efficient search and navigation are of

Rating: (out of reviews)

List Price: $ 30.00

Price: $ 17.73