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

Popular Posts