JSON Feed for Wordpress

Filed under: Javascript, Miscellaneous — Eike @ April 19, 2009 11:38 pm

JSON is short for Javascript Object Notation, a by now rather popular data format that is easy digestible by javascript functions (it is javascript, after all). So with JSON it is much easier to pull in data from other sources and web sites than with RSS or other XML-based formats.

Mattias Hising of Front-End Book wrote a Wordpress plugin that generates  a JSON feed from the latests posts of a Wordpress blog.  If you’re already using a Javascript library in your site then it will take only a few lines of script to include the feed your site (example code for Jquery is included in the post I linked above).

I think I will investigate if there is anything comparable for Joomla – this is such a small but useful thing.

    Forcing a link target on module links

    Filed under: Javascript, Programming — Eike @ November 10, 2008 10:49 pm

    In the comments Mark asked for a way to open link from the module in a new window. Since others might be interested I make this a blog post, but since I’m lazy I’ll make the post about the most simple way to do this.

    Well, the easiest way is to set a target for the links, and the easist way to achieve that would be, as far as the place here module is concerned, to go to the modules/mod_placehere/tmpl directory, open the template(s) in an editor and hardcode the target into the code. For the readmore link this would look like this:

    <a target=”_blank” href=”<?php echo $article->readmore_link; ?>” class=”readon<?php echo $params->get( ‘pageclass_sfx’ ); ?>”>

    The bit right after the anchor – target=”_blank” – forces a new window or a new tab, depending on browser and browser configuration.

    This method has some drawbacks, two of which I will adress here: One, it does not work with the module for Joomla 1.0.x (which does not use templates) and b) it means you code will not validate, since target is not a valid attribute in XHTML. We will cheat a bit and hide the target attribute from the validator by setting the target with Javascript.

    This could be done with a script that looks like this:

    <script type=”text/javascript”>

    links = document.getElementById(‘leftcolumn’).getElementsByTagName(‘a’);
    for(i=0;i<links.length;i++) {
    links[i].target = “_blank”;
    }

    </script>

    which you would have to place at the bottom of your page. But what does this actually do?

    To understand these few lines it helps to understand concepts like “DOM”, “chaining” and “iteration”.

    DOM is the “Document Object Model”. In the olden days a HTML document used to be a long list of characters, a.k.a a string. If you wanted to find a specified segment in the document the browser had to search through the whole string (which was a mix of the HTML formatting and the content), a cumbersome and not particularly efficient process. Modern Browsers have a different way – they represent a document as a collection of parent- and child elements (where every child can be in turn a parent to other childs). This allows for more efficient methods, like getElementById() which targets an element with a unique CSS Id, or getElementsByTagName, which collects all Elements of a given type. Methods like this can be chained.

    Functions (which in some contexts might be called “methods”) have usually a return value that can be assigned to a variable. If you do something like

    <script type=”text/javascript”>
    function test() {
    return “this is a test”;
    }

    toast = test();
    </script>

    the variable toast will hold the return value of the function test (i.e. “this is a test”). This is only useful when you plan to use the return value somewhere in your function script; on the other hand assining a value to a variable takes work both from you and the browser, and you don’t want to waste the work if you do not need the variable later on. In comes the concept of chaining, which allows you to skip one (or multiple) assignments, because, instead of writing

    <script type=”text/javascript”>

    temp = document.getElementById(‘leftcolumn’);

    links = temp.getElementsByTagName(‘a’);

    </script>

    you can chain these method together with the dot notation like this:

    <script type=”text/javascript”>

    links = document.getElementById(‘leftcolumn’).getElementsByTagName(‘a’);

    </script>

    This will pick the element with the CSS Id of “leftcolumn” from your HTML document and search it for all links elements with the type of “a(nchor)”. The result will be stored in the variable “links”.

    “links” will now hold a list with all links in leftcolumn (also called an array). It will be a list even when there is only one link, since getElementsByTagName always returns a list. To assign a new property (like a target) to every element in this list you need to move from entry to entry, a process that’s called iteration. The easiest way to iterate through a list is a for-loop.

    <script type=”text/javascript”>

    for(i=0;i<links.length;i++) {
    links[i].target = “_blank”;
    }

    </script>

    First you will notice a bit with the dot notation. However this is not method chaining; “length” is a “property” of the variable links that refers to the number of entries in the list (you can tell easily tell the difference between a method call and a property, since a method call has brackets, or parenthesis or whatever the correct word is “()” ).

    The list has an internal counter that start with “0″ (this is a convention, it doesn’t have to make sense, even if it seems more intuitive to most people to start a list with 1). So the first entry of the list is links[0], the second is links[1] etc.

    We do not know in advance how long our list is, but we can easily find out by accessing its length property. So we have our loop:

    <script type=”text/javascript”>

    for(i=0;i<links.length;i++) { }

    </script>

    which means to the browser: starting with zero; as long as the counter is smaller as the length of the list; increment (add one to) the counter; do whatever you are told to do inside the curly brackets (the counter needs to be smaller than the list length since the list starts with 0; if the length is ten the the last list element ist links[9]).

    So there we are again with our complete script:

    <script type=”text/javascript”>

    links = document.getElementById(‘leftcolumn’).getElementsByTagName(‘a’);
    for(i=0;i<links.length;i++) {
    links[i].target = “_blank”;
    }

    </script>

    This sets the target property for every item of the list (i.e. it creates a target attribute on every link).

    I said you would have to place the script at the bottom of your template. This is because the script cannot successfully execute before the element with the ID of ‘leftcolumn’ exists in the page. If you want to use in in another place, or in an external script file (best way) you can use the onload event handler.

    Events are mostly responses to user interaction (click, mouseover, mouseenter etc). An event handler allows you to assign a response to an event.

    A page load is also an event. It is executed when the page and the related assets (images, script files etc) are fully loaded, making sure that every element you script needs already exists. So you could place the following in the head of your template file:

    <script type=”text/javascript”>

    window.onload = function() {
    var links = document.getElementById(‘leftcolumn’).getElementsByTagName(‘a’);
    for(i=0;i<links.length;i++) {
    links[i].target = “_blank”;
    }
    }
    </script>

    Onload is is a method of the window object (Document Object Model, you remember?). There are some other elements with a onload event (images for example), but mostly this is used on the window itself. For the load event we define a so called “anonymus function” (which is called anonymus because it does not have a name. Duh).

    So the above script works on every Joomla template where there is an element with the ID of leftcolumn that contains one or more links. Naturally this works with other ids to.

    Of course most joomla templates now include the mootools javascript library which means that you could rewrite the above as

    <script type=”text/javascript”>

    window.addEvent(‘load’, function() {
    $$(‘#leftcolumn a’).setProperty(‘target’,'_blank’);
    })
    </script>

    which is an altogether more reliable and elegant way of doing things, but you wouldn’t have learned anything that way.

      Are inline elements supposed to have a line height and other miscellania

      Filed under: Javascript, Miscellaneous, Programming — Eike @ August 25, 2008 12:01 am

      I’m currently swamped with work and don’t have much time for blogging. But for those of my visitors who do their own HTML and Javascript I thought I share some programming problems I had in the last two days and their solution where I found one.  It might be that these are things should be clear from reading the relevant standards, but I have to admit that I find the standards for HTML and Javascript hard to read and even harder to understand; my usual tactic is to look how others are doing it and follow the majority.

      (more…)

        And another problem with javascript libs

        Filed under: Javascript — Tags: — Eike @ March 26, 2008 2:57 am

        A while ago I wrote about why javascript libraries are not necessarily helpful in my line of work (namely because of their high potential for abuse). Just now I stumbled upon another problem that makes them even less useful for me.

        A javascript lib provides – in theory – a common framework to write reusable and exchangeable modules and widgets that can be distributed over the web and plugged into existing applications. After all we all use a common code base, so there is no room for conflicts, or is there.

        Actually there is. Today the attempt to use three different prototype based widgets (and the subsequent attempt to find replacements) landed me right in version hell. Evidently every prototype based snippet uses a different version of the lib and backwards compatibilty, if at all intended by the prototype makers, is extremly limited. I’m not sure that it is actually faster if I write the required functions myself, but I bet it’s a lot less frustrating.

        And while I’m at it, here’s a heartfelt “Fuck you!” to all you browser manufacturers out there. I don’t know if you know how much unpaid overtime your crappy software causes for people like me, but my guess is you know it and break things on purpose. Oh well, who needs sleep anyway.

          Move Javascript to the bottom of the page

          Filed under: Javascript, Programming — Tags: , — Eike @ February 18, 2008 12:32 am

          I have blogged about this before, but right now I’m happy to repeat myself: The Yahoo Developer Network has excellent advice on how to optimize load time for your web pages, and the best thing is that so much of it can be easily implemented.

          Yahoos Rules for High Performance Web Sites start from the somewhat amazing observation that it’s not so much the response time of the server the time it takes the server to generate the page that slows down a web site but the things that happen after the HTML has been sent to the client.

          Most relevant for my case was that a) the browser makes a new http request for each ressource (style sheet, script, image etc) in the page (and the more request the slower the page) and that with external javascript files progressive rendering is blocked for all content below the script, meaning the rest of the page will not render before the script files are downloaded. An easy workaround is to call the scripts near the page bottom (though there might be scripts where this is not possible).

          I’m working on a site that uses prototype and various parts of the scriptaculous effects library, and I ended with six external javascript files. When I moved the script tags from the head section to the bottom of the page the load improved from about six seconds to two seconds (how do I know? I used Yahoos yslow to measure site performance).

          Now you might say that two seconds over a DSL connection is still pretty slow. But so far I have tripled load speed and it didn’t cost me more effort than a single cut and paste action – I call that amazing.

          I think most of Yahoos rules make sense only if you work on large sites with tens of thousands millions of visitors – I certainly will not set up a Content Delivery Network for a site with a few hundred visitors per day. Even so I think this proves that looking at the big boys can be a valuable excercise for us one man shops.

          I any case I’ve ordered Steve Souder’s (Yahoo! performance chief) book High Performance Web Sites – I don’t know if there’s anything in it that I couldn’t find as well on the YUI-Blog, but to buy the book seems a nice way to appreciate his work.

            Adventures in Javascript: The mighty search by postal code

            Filed under: Javascript — Tags: — Eike @ January 6, 2008 7:35 pm

            I’m currently suffering from a cold (yes, again), and I’m not fit to do anything useful. But at least I can share a gem of client side programming I found in a friends website when he asked me to have a look at the site – he wasn’t quite satisfied with the results his contractor had delivered.

            The site supposedly allows you to search for a shop by postal code. I was somewhat amazed: a search by postal code seemed somewhat excessive given that the company has only 15 shops in all of germany. I was even more suprised that the search field would not accept partial input – with this kind of search you would usually enter “1″ (instead of a full five-figure zip code) to find all matches in in Berlin and Brandenburg, I got an error message instead. When finally it turned out that the search returned always the same result (a list of all fifteen shops) no matter what I went looking for the code behind that “feature”. I found the following snippet of Javascript:

            function plzSuche(id, url) {
            
             if(document.getElementById(id).value.length<5
             || isNaN(document.getElementById(id).value)){
            
              document.getElementById(id).style.color='red';
            
              alert("Die Postleitzahl ist fehlerhaft");
            
             } else {
            
              top.location.href=url;
            
             }
            
            }

            In case you don’t speak javascript: this function checks if the value of an input field is numeric and has at least five digits (hint: while a german postal code is always a number with five digits not every number with at least five digits is a valid german postal code). If the value is too short or not a number the function returns an error message. It is not clear what is the purpose of that, since all the function does is to redirect the user to an url that is passed to the function as parameter and is in no way computed from or even connected to the user input. So this is not only useless, since it expects a valid input for the ever same result it’s quite annoying.

            I’m not the worlds greatest developer and have probably no business to lecture others on what they should do or not do. But anybody who comes up with bogus code like that and actually charges his client money is a fraud and should consider to pursue some other career than web programming (allegedly used car salesmen are allowed to get away with stuff like that).

              Yahoo Goodies and a Reminder about Open Standards

              Filed under: Javascript, Programming — Tags: , — Eike @ December 6, 2007 12:51 pm

              These days it’s always Google-this and Google-that, and of course I appreciate all the cool stuff they do – but other people do great things too, and in this case it’s even another search engine company: Yahoo has released a new version of their Yahoo User Interface library (covered in their blog here, download and documentation is here). I haven’t used YUI for serious projects, because I rarely do something like rich interface applications and I do not like to include large libraries when it’s not strictly necessary. But I played around with the examples enough to say that’s it cool and useful and well documented, so if you need an animation framework or DOM utilities or controls from color picker to rich text editor or a JS/Flash hybrid charts widget or JSON utilities.. well you see it’s a pretty complete list. And apropos of nothing I include here again a link to Christian Heilmanns website – he works for Yahoo and is testing the YUI lib for the european market, and besides he has as always a number of good blog posts on JS that are helpful for javascript developement even if you don’t plan to use this library (or any library).

              (more…)

                Chris Heilmann: Seven rules of Unobtrusive JavaScript

                Filed under: Javascript — Tags: — Eike @ November 13, 2007 11:23 pm

                Unobtrusive Javascript is Javascript that latches into a page without the need to mix javascript event handlers  and HTML.  Chris Heilmann has a good article about the “Seven rules of Unobtrusive JavaScript” – there is a short summary on his blog and an expanded version here.  If you are not familiar with unobtrusive javascript this is a good start, if you use it regularly and want to spread the gospel this is a good list to prepare for a presentation, so you should read it in any case.

                  Drop shadows: This one works amazingly well

                  Filed under: Javascript — Tags: — Eike @ November 9, 2007 12:53 am

                  What is it with graphic designers and shadows? Why are they so fond of little boxed and widgets and thingummies that drop they shadows any old way around the page?

                  That was a rethorical question, so no need to answer. Anyway I’m currently working on a wordpress project that has a lot of little boxes with shadows in the design, and rather than fiddling with nestes divs and images and replacement graphics for browsers that do not support opacity in png images I looked for a javascript solution.

                  I find that I rely more and more on javascript for layout tasks – I guess many people do by now, especially since most js libraries include now tricks for eye candy (rounded corners etc). Cleaner Markup is one advantage, although one could argue that a dynamically generated mess is a mess nonetheless. But then neither the maintainer of the site nor the validator will ever see the generated markup, so that’s okay.

                  But the real advantage over a CSS is solution is that you do not have to rely on hacks and workarounds to compensate for different implementations of CSS in the various browsers; instead Javascript calculates the differences programmatically.

                  I learned once again that this is a superior approach when I tested Erik Rassmussens drop shadow library for my project (built on top of prototype which suits me fine since prototype comes bundled with wordpress anyway) . It worked right out of the box  for every browser I tested, including the new Beta for Safari 3 for Windows. Actually in my case I needed a minor change to make it compatible with another script I was running ( the shadower lib clones the element that gets the shadow, so suddenly I had the same id twice), but it still beat the usual trial and error with CSS declarations.

                  So congratulations to Erik Rasssmussen, not only for a great piece of Javascript but also, and more so, because he just got married and is now on his honeymoon. Herzlichen Glückwunsch!

                    A Problem with Javascript libraries

                    Filed under: Javascript, Programming — Tags: , — Eike @ September 14, 2007 5:55 pm

                    A couple of days ago thelist – the mailing list of the evolt web developer community – had a short discussion about javascript libs (like e.g. jquery). Do they help with coding or not – i.e. do they help you to become an actual programmer or are they a simple way to do nifty stuff that you don’t actually understand?

                    I couldn’t contribute to the discussion, but still I’d like to mention here one of my problems with libraries. I often take over maintenance for sites that have been deserted by their original programmers, and usually when one of these web geniuses spontaneously combusts he burns with him all documentation. One of the sure signs of a web prodigy is that comments in the frontend code usually fail to tell anything useful. Instead I find little essays on why “Javascript sucks”, which is why they have used this amazing library (usually nebulous 0.1 or the promiscuous 0.0.5 pre-alpha) that allows for otherwise unsurmountable tasks like adding a rollover to an image or toggle display of a named element (and even if they used one of the better known scripting frameworks there are still at least a ten or twelve to choose from). So instead of programming in the one language javascript, which I by and by get the hang of (mostly due to Christian Heilmanns excellent book and web site) I suddenly have to look up documentation for a dozen or so libraries. And sometimes I wonder why my predecessors bothered at all to include a couple of hundred kb worth of Javascript when they then decided to rather use some method they’d concocted themself.

                    This is of course not an argument against libraries – I think by now it would be somewhat insane to built a Rich Interface Application without a javascript framework – but I still have to say that the purpose of libraries is often defeated at my end, when simple Javascript would be much easier to understand and maintain.

                    My suggestion would be not to use libs for the more mundane tasks but rather small, well documented scripts, never to include a library (or worse, multiple libraries) just because it has one effect that you particularly like and, if you can’t help to use a library then to actually use it and not replace parts of it with your own functions.

                    And if you are interested in Javascript your really should visit Chris Heilmanns web page wait-till-i.com (it feels a bit strange to advertise for him, since he’s some kind of web guru and I’m a goofball from Berlin, but still). While many people still look at JS as something that is slapped on top of a web page he sees it as a regular programming task, which means that the task at hand gets analyzed step by step before he starts writing code. I tried it and was amazed how much time you can save by taking the long way round.