Web development done well: WordPress web coding standards

11 10 2014

We all know that mess that grows in CSS, JavaScript and HTML files. There is no compilers as in static typed programming languages that will keep you from doing that mess bu there are Clean Code standards.

The team working on files should keep common standard and follow best practices. It is a failure if each team member has his own preferences and style and writes his parts with his own conventions. WordPress recommendation is:

"All code in any code-base should look like a single person typed it, no matter how many people contributed." – Principles of Writing Consistent, Idiomatic JavaScript

WordPress has its standards. Due to its opensource nature these are vital to keep an order in their web templates and sources. I follow most of their recommendations:

Advertisements




jQuery: prevent copying elements from webpage

4 10 2014

Want to prevent users copying text or images on your website? Or maybe you need to add custom behaviour on Ctrl+C click event?

With jQuery you can intercept the event of copying, pasting, cutting or dragging & dropping the element on your webpage.

Prevent copying

In my case I needed to prevent copying images on webpage (the whole body). This is the method I call on document.ready callback:

var preventCopyPaste = function(){
	$('body').bind('copy paste cut drag drop', function (e) {
   		e.preventDefault();
	});
};

If you need any other custom action to be performed instead of preventing default behaviour, just implement it in method body.

Test it!

Try to copy any image from karomile.com, where I used this method. If you manage to do it – let me know how you did it. I’ll make it even more bulletproof :)

I suspect that there is one way of doing it…

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





JS: infinite scroll examples

30 08 2014

There are few alternatives to implement infinite scrolling web pages, like facebook or twitter.

The site: http://www.sitepoint.com/jquery-infinite-scrolling-demos/ lists the best ones and shows some examples of usage with clues when which solutions will fit, and in which cases will not.

One of the solutions I am going to deploy on karomile.com soon.





karomile.com

9 08 2014

karomile.com was supposed to be a simple in a design but rich in content. This is a karomile’s photo site developed by me, according to her concept and design. After the PayTogether Android app, this is another project in my portfolio – web development is my skill as well (also in much more advanced designs, responsive layouts and JavaScript logic).

Site design is very nice, and makes perfect match with brilliant photos:

 

krmlprtscrn

Technically it is a web page with client side processing, made with HTML, CSS and JavaScript with few JS libraries like Unveil, Masonry, ImagesLoaded (read more here) and Google Analytics, not to mention jQuery :) CSS has media queries to make it responsive for mobile devices.

Site will evolve, since the content will get constantly updated and maybe technically I’d need to respond to it (for example by paging or endless scroll), so don’t be surprised if current site layout does not match the screenshot above :)





Web dev: Responsive image grid (that is not perfect but works)

26 07 2014

Worth noting and well working way to implement photo grid on website, is presented by Ali Jarafian on his website:

http://alijafarian.com/responsive-image-grids-using-css/

The ‘float: left;‘ type of design has few drawbacks in my opinion:

  • One is that you need to calculate the margins carefully and put the calculation result in few places in css (so changing the margin requires change in few places in css file).
  • And the second is that when one of the items is accidentally higher than the rest, the grid will not scale properly – I mean that one grid element will seem to be empty. This is because it will move to next grid cell if it cannot fit to the previous one.

Nevertheless that works. Personally Implement such kind of layouts without <ul> but on divs instead of <li>. This is simply because <li> are not beneficial for me – <div> is enough. I find <li> beneficial when business logic requires to append() or prepend() new items. In my project (static photo gallery) it is not a case.





Apache DefaultHttpClient Tutorial: execute HTTP GET request with params and BasicAuthentication

11 05 2013

When dealing with REST webservices, the HTTP GET request is commonly used (very often with params). Apache’s DefaultHttpClient has convenient methods that utilize making such requests. This is how I do it:

Request data

the URL that I am going to execute is:

http://www.example.org:8001/rest/sendMessage

GET request params are as follows:

  • body: message body (content)
  • from: sender’s name
  • to: recipient’s name

so the URL with params attached will look like this:

http://www.example.org:8001/rest/sendMessage?body=hello&from=jack&to=bill

Prerequisities

If your JRE is not equipped with Apache DefaultHttpClient, then you need to download two jars (I recommend to use version no older than 4.2.1):

  • httpclient-4.2.1.jar
  • httpcore-4.2.1.jar

1. Create URL

You can do it in two ways: hardcoded or objective.

Hardcoded version is simply creating String variable like this:

String url = "http://www.example.org:8001/rest/sendMessage?body=hello&from=jack&to=bill";

It is not convenient, because You have to converts this String to URI object, and encode it. The url above does not need encoding, but it would, if for example message content would contain spaces (The space is encoded to %20). So if body would be:

hello world

then the param would be encoded to:

body=hello%20world

More about ecoding you will find on wiki page here.

Objective version requires httpclient in version 4.2.1 or higher. That release has URIBuilder:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.example.org").setPort(8001).setPath("/rest/sendMessage")
.setParameter("msg", "hello")
.setParameter("from", "jack")
.setParameter("to", "bill");
URI url = builder.build();

the build method is encoding the url automatically, so the result uri is ready to execute. In other words you can write:

.setParameter("msg", "hello world")

without taking care about encoding – the builder will do it for you. If you do not need params, then you simply omit the setParameter() methods.

2. Create HttpGet instance

HttpGet request object  is created with url:

HttpGet httpget = new HttpGet(url);

3. Create Http Client

The DefaultHttpClient is powerful enough in most cases. The client is responsible for executing requests:

DefaultHttpClient httpClient = new DefaultHttpClient();

4. Provide BasicAuthentication credentials (Optional)

If your REST API is protected with BasicAuthentication you can add an Authentication Header to your HttpClient:

Credentials credentials = new UsernamePasswordCredentials("username", "password");
httpClient.getCredentialsProvider().setCredentials(newAuthScope("www.example.org",8001), 
		credentials);

5. Execute GET request

Now it’s time to execute request on client and retrieve the response:

HttpResponse response = httpClient.execute(httpget);

6. Handle all exceptions

There are several exceptions thrown by methods above. Your IDE will enforce you to handle them. Please see my implementation in snippet below.

7. See my complete source code :)

If you have problems building it up all together, here is my full implementation:

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;

public void sendTestMessage() {
    try{
        // build URL
	URIBuilder builder =newURIBuilder();
	builder.setScheme("http").setHost("www.example.org").setPort(8001).setPath("/rest/sendMessage").setParameter("msg","hello").setParameter("from","jack").setParameter("to","bill");
	URI url = builder.build();

	HttpGet httpget =newHttpGet(url);// Execute HTTP Get Request
	DefaultHttpClient httpClient =new DefaultHttpClient();
	Credentials credentials =new UsernamePasswordCredentials("username", "password");
	httpClient.getCredentialsProvider().setCredentials(newAuthScope("www.example.org",8001), 
				credentials);

	HttpResponse response = httpClient.execute(httpget);
    }catch(ClientProtocolException e) {
	e.printStackTrace();
    }catch(IOException e) {
	e.printStackTrace();
    }catch(URISyntaxException e) {
	e.printStackTrace();
    }
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Javascript: JSON tutorial

2 03 2013

JSON is a notation derived from Javascript. It is open and human-readable, therefore commonly used with other technologies (see this post, showing how to use it with Java/Android). Here are some basic operations with JSON in JavaScript:

1. Create simple JSON

var jsonMessage = {
    "message": "statusUpdate",
    "object": "object-1"
}

This is how result will look like:

{
	"message":"statusUpdate",
	"object":"object-1",
}

now you have a JSON variable made as simple String. It would be more useful with parameters, so see the next point.

2. Create parametrized JSON message

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
	"message": changeType,
	"object": objectId
}

The result will look exactly the same as in point 1.

Here the JSON message is created with two variables, which is the real life example, since values are often dynamic.

3. Adding new key to existing JSON

When we have JSON message that has to be extended (new key added) it is as simple as follows:

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
        "message": changeType,
	"object": objectId
}

jsonMessage.info = "More info...";

The resulting JSON will look like below:

{
	"message":"statusUpdate",
	"object":"object-1",
	"info":"More info..."
}

4. Create and add JSON Array to JSON message
JSON Array is created from Javascript array, so to create id just create new variable and add it to JSON, as a new element (like in point 3):

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
	"message": changeType,
	"object": objectId
}

var jsonArray = ["one", "two", "three"];
jsonMessage.myArray = jsonArray;

And this will be the result:

{
	"message":"statusUpdate",
	"object":"object-1",
	"myArray":[
		"one",
		"two",
		"three"
	]
}

5. Change element in JSON Array
This is as simple as:

var changeType = "statusUpdate";
var objectId = "object-1";

var jsonMessage = {
	"message": changeType,
	"object": objectId
}

var jsonArray = ["one", "two", "three"];
jsonMessage.myArray = jsonArray;
jsonMessage.myArray[1] = "changed";

So that we now have an output (compare it to output myArray in point 4):

{
	"message":"statusUpdate",
	"object":"object-1",
	"myArray":[
		"one",
		"changed",
		"three"
	]
}

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!








%d bloggers like this: