Nov 30, 2009

Walking around with JQuery

Selecting, traversing, and manipulating DOM elements is relatively easy with JQuery. You can play with them and do many cool things.

Let’s start with simple selecting. We may need a list of all the images in a document. This can be achieved very easy:

 $("img")
Let’s hide them:
       $("img").hide();

Now, if we don’t want all images but only images located in div tag we can do this:
       $("div > img").hide();
Selecting element with a specific id is very simple:
       $("#myId")
And we can obtain a list of images located in this specific div with the expression:
       $("#myId > img")
We can get a list of elements from a certain type and having a specific class. For example we can get a list of all div elements who have css class text and hide them.
       $("div .text").hide();

If we get a list of elements from another source (for example some function) and we want to obtain only the ones with a exact property we can do it with filter. In this example I’ll select all div elements and check them:
       $("div").filter(".text").hide();

After hiding all elements we may want to show the first one. Here we have several approaches. If the circumstances are right we can just select the first element:
        $(".text:first").show();
Of course we may want the last one:
        $(".text:last").show();
We can get the n-th element using eq. Keep in mind that arrays start from 0.
        var n = 1; // we want the second element in reality
        $("div:eq("+n+")").show();
We can obtain all elements on a page that contain a specific text:
        $("div:contains(text)"). css("background-color","yellow");
Or we can obtain all div elements containing a specific text (text) and not specific css class:
         $("div:contains(text):not(.title)"). css("background-color","yellow");
I’ll continue with more later.

Nov 16, 2009

How to write your own jquery plugins – random size plugin

Let’s continue our plugin example. I’ll change the plugin from the first post to something a little more fun.

RandomSize plugin – it will change the font size of all inner html elements with random values. For this goal we need a list of 'this' element children.

var c = $(this).children();

We can generate random numbers with the expression:

Math.floor(Math.random() * max)

where max is our max value. Also it is better to have a min value because people can’t read font with size 1. So our expression will evolve this way:

Math.floor(min + Math.random() * (max - min))

Here is the plugin code:
(function($) { 
$.fn.randomSize = function(settings) {
    var config = { 
     'min':'10', 
  'max':'30',
  'fontWeight' : 'bolder'};
    
     if (settings) 
      $.extend(config, settings);
 
     this.each(function() {
  var c = $(this).children();
  c.each(function() {
   var rand = Math.floor(
    parseInt(config.min) + 
    (Math.random() * 
    (config.max - config.min)));
    
   var cssObj = { 
       'font-size':rand + 'px', 
       'font-weight':config.fontWeight};
   $(this).css(cssObj);
  });
   
     });
 
     return this;
};
})(jQuery);

Sample html:
<div>
 <span>Element 1</span>
 <span>Element 2</span>
 <span>Element 3</span>
</div>

And we call it like this:
$("div").randomSize();

How to write your own jQuery plugins

Packing your code into plugins will make it easier for maintenance and reuse. JQuery plugins can accelerate the development process and simplify the final product. Writing your own plugins isn’t hard either.

Ok, let’s start with a very simple plugin. I have very little imagination, so my plugin will do very stupid work – it will change the font size and weight of an element. I’ll call it … demoPlugin. Original, isn’t it?

Let’s define it:
$.fn.demoPlugin = function(settings) {
}
And we will call it this way:
$("div").demoPlugin();
Some initial configuration like this:
var config = {'fontSize' : '30px', 'fontWeight' : 'bolder'};
And we will extend it with the parameters provided by the user.
if (settings) 
 $.extend(config, settings);
And our main code goes here:
this.each(function() {
   $(this).css({

      'font-size':config.fontSize, 
      'font-weight':config.fontWeight});
       });
Here is the full plugin code:
(function($) { 
 $.fn.demoPlugin = function(settings) {

   var config = {
    'fontSize' : '30px', 
    'fontWeight' : 'bolder'};

       if (settings) 
    $.extend(config, settings);
 
       this.each(function() {
   $(this).css({

      'font-size':config.fontSize, 
      'font-weight':config.fontWeight});
       });
 
       return this;

  };
})(jQuery);


Don't forget to return this at the end. It is very important in order to use chain calls.

I’ll continue with less trivial plugin example later.

Next plugin article.

Nov 7, 2009

Selecting elements with JQuery – examples

JQuery Library is a very convenient way for selecting page elements. You can select elements by type, by parent, by index and so on.
The easiest way to select an item is by its id. I’ll use it for my control buttons. For all three of them I’ll bind functions to their click event.
Here are my buttons as HTML code:

<button id="all">Show/Hide ALL</button>
<button id="nth">Show/Hide nth</button>
<button id="odd">Show/Hide ODD</button>

And my test javascript code here:

$(document).ready(function() {
 $("#all").click(function () {
  alert("Clicked ALL");
 });
 $("#nth").click(function () {
  alert("Clicked NTH");
 });
 $("#odd").click(function () {
  alert("Clicked ODD");
 });
});

Now we will change the code to select and toggle the desired elements. We will start with the first because it is the easiest of them all. Selecting elements by type in JQuery is very simple and is done through their name. To select all paragraphs we simply need to use $("p") and call toggle on it. $("p") will return all matched elements – all ‘p’ tags on the page.
The code:
$("#all").click(function () {
 $("p").toggle();
});

To select the n-th element – in our case the third one we will use $("p:eq(3)") and to select all odd paragraphs $("p:odd").

Here is the full example code:
<html>
<head>
<title>Selecting elements with JQuery</title>
<script  src="jquery.js"></script>

<script>
$(document).ready(function() {
 $("#all").click(function () {
  $("p").toggle();
 });
 $("#nth").click(function () {
  $("p:eq(3)").toggle();
 });
 $("#odd").click(function () {
  $("p:odd").toggle();
 });
});
</script>
</head>
<body>
JQuery example - selecting items.
<div>
<p>Paragraph 0</p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</div>
<div>
<table>
<tr><td>All Paragraphs: </td><td><button id="all">Show/Hide ALL</button></td></tr>
<tr><td>Third paragraph: </td><td><button id="nth">Show/Hide nth</button></td></tr>
<tr><td>All odd paragraphs: </td><td><button id="odd">Show/Hide ODD</button></td></tr>
</table>
</div>
</body>
</html>

As you can see – very simple and intuitive.

Nov 2, 2009

How to make very simple JavaScript slideshow with JQuery

I’ll continue my article about JQuery Effects - with this one. It would be short information on how to make custom JQuery slideshow animation.

Let’s start with a div containing our images. Here is the code:

<div id="slideshow">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
    <img src="img4.jpg" />
    <img src="img5.jpg" />
    <img src="img6.jpg" />
</div>

I’m not really good at using CSS so it would be pretty simple.

#slideshow {
    position:relative;
    height:200px;
    width: 210px;
}
#slideshow img {
    position:absolute;
    top:10px;
    left:5px;
}

I’ll use some initializing code to hide all the images, and then I’ll show only the first one. Here is the code packed in a function.

function init() {
 $('#slideshow img').hide();

 $('#slideshow img:first').show();
}

And now, we must write the logic of our slideshow. We need to obtain the visible image, hide it and show the next one. When we hit the end, we need to revert back at the first element.
So let’s start with obtaining the visible image. It is simple with JQuery selectors:

var $top = $('#slideshow img:visible');

And get the next image:

$next = $top.next();

This won’t help us when we reach the last image. I’ll make a check for the last element:

var $next;
 if($top.next().length > 0)
  $next = $top.next();

 else
         $next = $('#slideshow img:first');

And now the action:

$top.hide();
$next.show();

Our slide function must be called on a regular basis. We will obtain this with the JS function setInterval.

setInterval( "slide()", 3000 );

And here is the full code:

<html>
<head>
<title>JQuery Slideshow examples</title>
<style>

#slideshow {
    position:relative;
    height:200px;
 width: 210px;
}
#slideshow img {
    position:absolute;
    top:10px;
    left:5px;
}
</style>
<script  src="jquery.js"></script>
<script>
function init() {
 $('#slideshow img').hide();

 $('#slideshow img:first').show();
}
function slide() {
    var $top = $('#slideshow img:visible');

    var $next;
 if($top.next().length > 0)
  $next = $top.next();

 else
        $next = $('#slideshow img:first');

 $top.hide();

 $next.show();
}

$(document).ready(function() {
 init();
    setInterval( "slide()", 3000 );
});

</script>
</head>
<body>
<div id="slideshow">
    <img src="img1.jpg" />

    <img src="img2.jpg" />
    <img src="img3.jpg" />
 <img src="img4.jpg" />

 <img src="img5.jpg" />
 <img src="img6.jpg" />
</div>
</body>
</html>

Working demo

Oct 27, 2009

Intro to Struts (1.x) - Practical Example

This would be simple and easy tutorial on how to use Apache Struts in Java web projects.

What do you need for this tutorial?
  • Java
  • Tomcat
  • Java IDE (For example Eclipse or NetBeans)
  • Struts 1.x version http://struts.apache.org/download.cgi#struts1310

I’ll write another document for Struts 2.x. They are different frameworks with somehow different ideas but both are excellent choice.

For clearness it would be very simple code - I won’t use packages or other good practices. Consider this only as an introduction not a reference.

Struts programming is centered at the MVC pattern. MVC stands for Model-View-Controller, an idea to separate the business logic, application data and the presentation layer. I won’t discuss here what the advantages of using MVC architecture in web application are – just make a fast search, there is plenty of information out there.

Let’s start with creating a new project. Our web application would ask visitors for a name and redirect them to a Hi! page. At part 2 it won’t like some of the visitors and will return back them with an error message.

Here is my directory and file structure for Struts1Example project:
Struts1Example
 src
  NameAction.java
  NameActionForm.java
 webroot
  WEB-INF
   classes
   lib
   struts-config.xml
   web.xml
  ask.jsp
  greet.jsp

Lets start with writing our ActionForm – I’ll name the class NameActionForm. It would be very plain – only one field and a setter-getter pair. Here is the code:

NameActionForm.java
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;


public class NameActionForm extends ActionForm {
 private String name = null;

 
 public void reset(ActionMapping mapping, 
    HttpServletRequest request) {

        this.name = null;
 }

 public String getName() {

  return name;
 }

 public void setName(String name) {

  this.name = name;
 }
}

And our action:

NameAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class NameAction extends Action {

 public ActionForward execute(ActionMapping mapping, 
    ActionForm form,
    HttpServletRequest request, 
    HttpServletResponse response) {
  return mapping.findForward("success");
 }
}

In Struts the Action class goal is to process a request, do the logic and pass a forward object (ActionForward). Our Action is very simple – it is doing nothing, just passes our forward object. The “success” forward is defined in our struts-config.xml.

We will have two jsp files – ask.jsp and greet.jsp. In ask.jsp we will ask visitors for a name.
ask.jsp
<%@ page language="java" contentType="text/html; 
  charset=utf-8" %>

<%@ taglib uri="http://struts.apache.org/tags-html" 
  prefix="html" %>

<html:html>

<head>
<title>Say Hi!</title>
</head>
<body>
 <html:form action="nameAction">
  What's your name?
  <html:text property="name"></html:text>

  <html:submit>Send!</html:submit>
 </html:form>
</body>
</html:html>

greet.jsp
<%@ page language="java" contentType="text/html; 
  charset=utf-8" %>

<%@ taglib uri="http://struts.apache.org/tags-bean" 
  prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" 

  prefix="html" %>
<html:html>
<head>
<title>Say Hi!</title>
</head>
<body>

Hi, <bean:write name="nameForm" property="name" />
</body>
</html:html>

And now the cool part – web.xml

web.xml
<?xml version="1.0"?>
<web-app>
  <display-name>Struts 1x Example</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
     org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>

      <param-name>config</param-name>
      <param-value>
       /WEB-INF/struts-config.xml
      </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>

 </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

And our struts configuration – struts-config.xml

struts-config.xml
<?xml version="1.0" ?>
<struts-config>

    <form-beans>
     <form-bean 
      name="nameForm" 
      type="NameActionForm"/>

    </form-beans>

    <global-forwards>
        <forward
            name="/nameAction"
            path="/nameAction.do"/>

    </global-forwards>
    
    <action-mappings>         
       <action path="/nameAction" 
         type="NameAction" 

         input="ask.jsp" 
          name="nameForm" >
        <forward name="success" 

          path="/greet.jsp"/>
        <forward name="failure" 
          path="/ask.jsp"/>

       </action>
    </action-mappings>
</struts-config>

struts-config.xml is used to initialize Struts. It describes the action mappings for the project and must be placed in the WEB-INF directory. We have a form-bean tag describing our NameActionForm and an action-mapping for our NameAction.

This is our base code. In some future post I’ll add field validation, error handling and some other good stuff.

Oct 22, 2009

Fun with JQuery Effects – few examples

You can use JQuery Effects in many different ways. I'll write few examples just to show how cool and fun is to work with this API.

Using toggle:

toggle.html
<html>
<head>
<title>JQuery examples</title>
<style>
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#our_button").click(function() {
$("#our_image").toggle();
});
});
</script>
</head>
<body>

<button id="our_button">Hide/Show</button> the image.
<br /><br />
<div id="our_image">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSMhLVeVRnBTwKXkBjFX-nOQusSJyKsneDo-yTxCWJtDGVFg2FMzr4vSEWTDjCm7WgGWW1KFYadgz0y3gyXd7kuBMcMIlWijcK3ikxqRVciTwJWdaaiT6Z62m6pGWQNhKILC2oWF4Hmw/s320/flower.jpg" />
</div>
</body>
</html>


And the result:


the image.



Using slide toggle:

slide.html
<html>
<head>
<title>JQuery examples</title>
<style>
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#our_button").click(function() {
$("#our_image").slideToggle("slow");
});
});
</script>
</head>
<body>

<button id="our_button">Hide/Show</button> the image.
<br /><br />
<div id="our_image">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSMhLVeVRnBTwKXkBjFX-nOQusSJyKsneDo-yTxCWJtDGVFg2FMzr4vSEWTDjCm7WgGWW1KFYadgz0y3gyXd7kuBMcMIlWijcK3ikxqRVciTwJWdaaiT6Z62m6pGWQNhKILC2oWF4Hmw/s320/flower.jpg" />
</div>
</body>
</html>


And the result:


the image.



Easy, isn't it? Tomorrow I'll continue with animate function.

Oct 12, 2009

More JQuery examples - Intro to JQuery - part 3

How to use JQuery filter? (Easy example)



Filter is used to filter some results from a set. (of course) For example let’s have a document with many divs in it. We want to select only the ones with css class “.text” and hide them. We can do this using filter.

At the beginning lets write some dummy html file with the basics in it. Here it is our filter.htm:

<html>
<head>
<title>Our JQuery examples</title>
<style>
.text {
}
.comment {
}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
// our javascript examples will go here
});
</script>
</head>
<body>
<!-- our text will go here -->
</body>
</html>


Let’s make some divs and set class text to some of them and comment to the others.

<div class="comment">
123
</div>
<div class="text">
This will be selected.
</div>
<div class="comment">
This wont be selected.
</div>
<div class="text">
This div will be selected.
</div>
<div class="text">
Selected!
</div>

This row will hide all divs with class text.

$("div").filter(".text").hide();

It would be easy to make a button that shows and hides these divs. Here is the full source:

<html>
<head>
<title>Our JQuery examples</title>
<style>
.text {

}

.comment {

}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#toggle").click(function() {
$("div").filter(".text").toggle();
});

});
</script>
</head>
<body>
Show and hide filtered divs. <br />
<button id="toggle">Toggle Show/Hide</button>
<div class="comment">
123
</div>
<div class="text">
This will be selected.
</div>
<div class="comment">
This wont be selected.
</div>
<div class="text">
This div will be selected.
</div>
<div class="text">
Selected!
</div>
</body>
</html>


Here is our work:


Show and hide filtered divs.

123
This will be selected.
This wont be selected.
This div will be selected.
Selected!

Intro to JQuery - part 1
Intro to JQuery - part 2

Sep 13, 2009

Web authorization and OAuth

OAuth is an open protocol that defines secure api authorization methods. More and more sites in internet adopt its idea and start to use it.

So what is so cool about it?
OAuth offers a way to work with protected data while securing sensitive user account information. Imagine you want to access your twitter, yahoo or google account from some third party site or application with someadditional functionality. What will happen if the consumer site or application is not so trustworthy and steal your account? OAuth is the key to protect your account in this case.
There is a very popular parallel in the web. OAuth is like the valet key that offers a limited use of your car. Not all cars came with valet keys but anyway it is a good comparison.

With OAuth the user grants access to his protected resources without sharing his username and password with third parties. Imagine a website that offers you great functionality to add and remove many Twitter followers. One way to use it is to share your credentials with it. The other is to use special token to give only few privileges but to protect your sensitive information.

Some terminology:
Service Provider – web service that offers some functionality to third parties.
Consumers – website or application that accesses protected resources of a Service Provider.

How to use it? Do I need to reinvent the wheel?
Nop. The wheel is invented. There are some ready libraries out there. http://oauth.net/code
Here is one useful tool http://googlecodesamples.com/oauth_playground/.

For more information on OAuth visit http://oauth.net/ .

Popular Posts