Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, September 16, 2008

Seperating visual effects from HTML using jQuery

I remember reading Matt Ryall's blog on 10 things every web developer should know a while back and I would like to highlight the clean code suggestion made there.

I'm migrating the existing Aflexi website to Drupal and at one point I came across an existing code which.. is not too ugly but hard to be integrated into its Menu feature. The code has a few divs that jQuery uses to create sliding effects, I could actually put them into the template page.tpl.php but using jQuery to inject them at the end of page is certainly a better practice.

So, in my template.php, I have:

$js[] =<<JAVASCRIPT
$('#nav').append('lots.of.divs'); // Here's the injection
$(document).ready(function() {
UiHelper.registerSlider('a.menu-1-1-2', '#sliderWso', '#pointerWso', 300);
...
});
JAVASCRIPT;
drupal_add_js(join("\n",$js), 'inline');


By the way, I make the divs a one liner using:

echo 'paste your html' | tr -d '\n'

Then, talking about injection, this is brought into my attention as well - jQuery-AOP.

- yc

Wednesday, July 30, 2008

Sliding down, Scriptaculous and jQuery

Haven't been hacking JavaScript "seriously" after a few years, I got myself back into doing it two days ago. I wanted a slide up/down effect on a panel when a button is hovered.

I first came across the Scriptaculous but I wasn't satisfied with the size of the JS files, Scriptaculous+Prototype+jQuery, as I use Thickbox as well (too bad, Lightview is not free).

I received some questions in Twitter and Facebook about "why both?", so I knew I needed a change unless I had a good reason. I then spent a bit of time in the morning to read the jQuery's documentation and found out that it's easier to get this done with it.

Here's the code comparison:

jQuery's Snip

jQuery(document).ready(function(){
jQuery("#woPageSelector").hover( function(){ jQuery("#woPageSelectorContent").slideDown(300); }, function(){ jQuery("#woPageSelectorContent").slideUp(300); } );
});


Scriptaculous' Snip

var mouseOverHandler = function(event) {
$('wpPageSelectorContent').slideDown({duration: 0.5, queue: {position: 'end', scope: 'pageSelectorsPanel', limit: 2}});
$('woPageSelector').stopObserving('mouseover', mouseOverHandler);
document.observe('mouseover', mouseOutHandler);

}

var mouseOutHandler = function(event) {
$('wpPageSelectorContent').slideUp({duration: 0.5, queue: {position: 'end', scope: 'pageSelectorsPanel', limit: 2}});
$('wpPageSelector').observe('mouseover', mouseOverHandler);
document.stopObserving('mouseover', mouseOutHandler);
}

$('wpPageSelector').observe('mouseover', mouseOverHandler);

By the way, if you really have to use Prototype and jQuery at the same time, you may want to read this page to prevent conflicts.

- yc, woohoo!

Monday, July 2, 2007

Son oh son.. JSON

Learning a new techy stuff every weekend of mine seems to have turned into a real habit. JSON (or you can call it Jason ;-)), not something entirely new but it has been really hot these days. It stands for "JavaScript Object Notation" and it exists today is to make the AJAX programmers life easier.

I will briefly show you how you can get a hang of it using a simple JSP file and a small piece of JavaScript (YUI). If you do not have an idea about AJAX yet, you'd probably want to read about it first before going beyond this paragraph.

An AJAX response in XML format requires writing client code to parse it into DOM model, for instance:


<bean>
<name>foo</name>
<description>foobar</description>
<id>10000</id>
</bean>


Then some annoying JSDom bits to extract the data, which I'm not going to write. As I could recall, my last time of writing AJAX and DOM stuffs was a year ago for a Java webapp which requires validating the form fields by sending synchronous request to webMethods endpoints.

This might just be another article about JSON which you have read before from other sites, yes, it is. Anyway, a response can also be sent in JSON (which is basically string then be evaluated using JavaScript eval() method), e.g.

{"name": "foo",
"description": "foobar",
"id": "10000"}



Data can then be extracted easily unlike DOM, e.g.

var jsonObj = eval("(" + responseText + ")");
var name = jsonObj.name;


Before I end this blog so that you can find out more by yourself ;-), this is the JSP used to generate the response:

<%@ page
language="java" contentType="text/json; charset=utf-8"
import="org.json.simple.JSONObject"
%>
<% response.setContentType("text/json; charset=utf-8"); %>
<%
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", request.getParameter("name"));
jsonObj.put("description", request.getParameter("description"));
jsonObj.put("id", new Long(request.getParameter("id")));
out.print(jsonObj);
out.flush();
%>
And this is the HTML used to send the request and receive the response:

<html>
<head>
<title>Test AJAX</title>
<script type="text/javascript" src="js/yui-2.2.2/yahoo/yahoo-min.js"></script>
<script type="text/javascript" src="js/yui-2.2.2/connection/connection-min.js"></script>
<script type="text/javascript">
function getAjaxRequest(url, callback){
return YAHOO.util.Connect.asyncRequest('POST', url, callback, "name=foo&description=foobar&amp;amp;id=10000");
}
</script>
</head>
<body>
<script type="text/javascript">
var callback = {

success: function(o){ alert("Successful: \n" + o.responseText + "\n" + o.getAllResponseHeaders)

var jsonObj = eval("(" + o.responseText + ")");

// Some reflection here
var jsonDump = "";
for(key in jsonObj){
jsonDump += key + ": " + jsonObj[key] + "\n";
}
alert(jsonDump);

},
failure: function(o){ alert("Failed: \n" + o) },
argument: []

}

getAjaxRequest("testJsonResponse.jsp", callback);
</script>
</body>
</html>

One final and common note though, if you ever come across designing a webapp with AJAX functionality, do keep the response format consistent, i.e. use application/xml OR text/json NOT both, so that you will not confuse the developers at another end of which they should expect.

- yc, raining

Saturday, April 28, 2007

Sexy Web-Design Trick

Here is something I shared with my colleagues previously in company's internal blog. Something quite useful to a web- designer or developer.


var tables = document.getElementsByTagName("table");

for(var i = 0; i < tables.length; i++){ tables[i].style.border = "2px dotted #000000"; tables[i].style.padding = "4px"; };

var divs = document.getElementsByTagName("div");

for(var i = 0; i < divs.length; i++){ divs[i].style.border = "1px dashed #dddddd"; divs[i].style.padding = "4px"; };


I'm using this as a Firefox bookmark, here's an example:

Image

- yc, stoning