Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

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.

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

Nov 13, 2008

Simple AJAX with JQuery(part 1) – ugly example

After getting some experience with JQuery from the previous tutorials, you may be ready for some fun. AJAX development is relatively easy with the JQuery framework.

For this part I’ll show how to use “load” in a basic example. We will have a online book and we will load the chapters without reloading the whole page. This is a stupid example, for many reasons. First – online publishers prefer more reloads. The AJAX functionality is a better decision for online business solutions, not for online reading. But I have no imagination for other relatively simple demo and I am lazy.

So – our example. It is an online book. We will select our chapter with prev(previos) and next buttons. The full ugly working example can be seen here - http://ldeveloper.hit.bg/book.load.html

We will store our chapter names in a JavaScript array:


var bookchapters = new Array( "chapter1.html", "chapter2.html", "chapter3.html" );



The load – loads a html and injects it into the DOM element. It can also filter the incoming document – very convenient if you don’t need the whole page.

So back to our example – the html:



<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<form>
<input type="button" value="Prev" id="prev">
<input type="button" value="Next" id="next">
</form>
<br>
<br>
<strong>Book Title</strong>
<div id="book">
</div>
</body>



And we load a chapter with the following(For this example our chapters are in a folder “book”):


$("#book").load("book/" + bookchapters[index]);



The whole code(html, js and css):


<html>
<head>
<title>JQuery and AJAX tutorial</title>
<style type="text/css">
#book {
background-color: #F0FFF0;
border : thin ridge;
height: 450px;
overflow: scroll
}
input {
background-color : White;
color : #006400;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var bookchapters = new Array( "chapter1.html", "chapter2.html", "chapter3.html" );
$(function () {
var index = 0;
$("#book").load("book/" + bookchapters[index]);
$("#prev").click(function () {
if(index > 0) {
index--;
$("#book").load("book/" + bookchapters[index]);
}
else {
alert("first chapter");
}
});
$("#next").click(function () {
if(index < bookchapters.length - 1) {
index++;
$("#book").load("book/" + bookchapters[index]);
}
else {
alert("last chapter");
}
});


});
</script>
</head>
<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<form>
<input type="button" value="Prev" id="prev">
<input type="button" value="Next" id="next">
</form>
<br>
<br>
<strong>Book Title</strong>
<div id="book">
</div>
</body>
</html>





Filtering the incoming page



This example shows how to use it. The “div:first” after the url in the load parameter string selects only the first div of the incoming document.


<html>
<head>
<title>JQuery and AJAX tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#page").load("in.html div:first");       
});
</script>
</head>
<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<br>
<div id="page">
</div>
</body>
</html>



And the in.html:


<html>
<body>
<div>
First part of the document that will be loaded!
</div>
<br>
<div>
Next part, that won't show into the other.
</div>
</body>
</html>



Nov 6, 2008

Intro to JQuery - part 2 - JQuery examples

If this is your first encounter of JQuery, I recommend the post – Intro to JQuery.

This is a short document on how-to use JQuery API. Necessary knowledge for this post includes JavaScript, HTML and CSS basics.


Let’s change the last example of the previous post a little. We can handle the logic without the counter variable:


<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
var c = parseInt($(this).html());
$(this).html(c + 1);
});
} );
</script>



We can add more complex code with the html(), not only one number. For example:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
$(this).html(String($(this).html() + "<br/><b>We added a row!</b>"));
});
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
This is our test div element.
</div>
</body>
</html>



Be careful to add a correct html for the html() function value or you will end with unexpected results.

JQuery have more methods for DOM manipulations. For full list of these methods I recommend reading the documentation - http://docs.jquery.com/Manipulation

Very power JQuery functionality is the opportunity to easily traverse the DOM tree. One very useful element in this part is the each(). It is used to execute a function within the context of every matched element. This is simple example of its usage:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div").each(function () {
$(this).css({border : "medium double Red", backgroundColor: "orange"});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div>First div element
</div>
<div>Second div element
</div>
</body>
</html>



And now a little more complex example:
The code bellow gets all the <p>(paragraph) childs of the <div> elements and sets them a css class “our class”. There are many other ways to achieve the same thing, this is just example of using each() and children().


<html>
<head>
<title>JQuery basic tutorial</title>
<style type="text/css">
.ourclass {
border : medium double #FFA500;
width: 90px;
height: 90px;
}

</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div ").each(function () {
$(this).children("p").each(function () {
$(this).addClass("ourclass");
});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div style="border : 1px solid Black;">First div element<div></div>
</div><br/>
<div style="border : 1px solid Black;">Second div element with two paragraphs
<p>First <b>p</b></p>
<p>Second p</p>
</div>
<p style="border : 1px dotted Black;">This is a paragraph but it is not a div child</p>
</body>
</html>

Oct 31, 2008

Intro to JQuery

JQuery is a lightweight JavaScript framework that got a lot of attention lately so I decided to write few rows about it.

This post-tutorial is recommended for people with basic javascript, html and css knowledge.

To run and test the examples in this tutorial, you need to save them as html pages. You can use any text editor like notepad or anything convenient.

What do you need to start using JQuery? Just download and save it in the same directory (I’ll call it jquery.js) and include the following code anywhere above your javascript code:


<script type="text/javascript" src="jquery.js"></script>



The best place for our javascript code is in the head section of the html document but you are not restricted to it. Anyway I’ll use the head section for most of my examples.

Ok, let’s use some basic functionality to test if we’ve done it right.

example1.html:

<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert('Works!!!');
} );
</script>
</head>
<body>
JQuery basic tutorial
</body>
</html>




So, what happens here? Nothing special, we just show an alert with text ‘Works!!!’.

$ function is a factory method (shortcut) for the JQuery object.


$(document).ready(function() {
// code
});



With $(document).ready we register our code to the ready event of the document. The above code can be shortened:


$(function () {
// code
} );



Selectors and events



In JQuery an element can be selected in different ways – by id, by element type, by css class and so on.
This is a simple code showing how to use events and selectors:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
alert("Click");
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
Div
</div>
</body>
</html>



The click(fn) binds a function to the click event of our matched element.
Let’s make our example a little more complex. We will count the clicks.


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function () {
$("#ourID").click(function () {
counter++;
$(this).html(counter);
});
} );

</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
0
</div>
</body>
</html>


Aug 22, 2007

Fun with GWT and Web 2.0

Simple and easy GWT tutorial and overview.

Introduction & Overview
I am mainly a server-side Java and C++ developer. I don’t have much time to loose with the View of the projects. But recently I had to make some Web User Interface with Ajax. I had some complicated and not functional JavaScript code which I had to debug. It is a really awful task for me. And then I just make a research for some useful Ajax tools and libs.
Why I like GWT. Of course because I can write java code and don’t bother with JavaScript. Also things that I find useful are in their first page : dynamic, reusable UI , simple RPC, browser history management, simple debugging, browser compatibility and so on. And of course it is released under Apache 2.0 license so you can use it in commercial products.

To understand this tutorial you need to have basic java and web knowledge.
Also it will be useful to have this installed:
1. Java SDK http://java.sun.com/javase/downloads/index.jsp
2. GWT http://code.google.com/webtoolkit/
3. Eclipse http://www.eclipse.org/

Hello World
At first glance GWT looks a little confusing, but it is far from the truth. In the matters of fact GWT is one of the simplest and easiest ways of making complex AJAX interfaces. Let us give a try. I will use eclipse for my tutorial projects.
You can create demo project in eclipse workspace using projectCreator tool:
projectCreator -eclipse TutorialProject
Then just call
applicationCreator -eclipse TutorialProject com.mycompany.client.MyApplication

Full description about how to get started with GWT you can find on http://code.google.com/webtoolkit/gettingstarted.html
After running this command you should have your project with some sources in it.
Now you are ready to start. First you must have MyApplication-compile and MyApplication-shell scripts. Run MyApplication-compile and you will see your application in hosted mode. You must see something like this.





Also you must have something like this code:
package com.mycompany.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
* Entry point classes define onModuleLoad().
*/
public class MyApplication implements EntryPoint {

/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Button button = new Button("Click me");
final Label label = new Label();

button.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (label.getText().equals(""))
label.setText("Hello World!");
else
label.setText("");
}
});

// Assume that the host HTML has elements defined whose
// IDs are "slot1", "slot2". In a real app, you probably would not want
// to hard-code IDs. Instead, you could, for example, search for all
// elements with a particular CSS class and replace them with widgets.
//
RootPanel.get("slot1").add(button);
RootPanel.get("slot2").add(label);
}
}


This is the code for our simple Hello World application that GWT create for us. And a html file MyApplication.html.

Let us change some stuff.
First make MyApplication.html look like this.



Then lets change our MyApplication:

public class MyApplication implements EntryPoint {

public void onModuleLoad() {
}
}
Now add a panel. Let it be VerticalPanel.
VerticalPanel verticalPanel = new VerticalPanel();

public void onModuleLoad() {

RootPanel.get().add(verticalPanel);
}
To this panel we can add any component we like. I choose to give a try to the menus.
First we need our horizontal base menu to which we will attach our menus.
MenuBar ourMenu = new MenuBar(true);
MenuBar baseMenu = new MenuBar();
After this we need our menu and some MenuItems and a command that will be run when somebody click on our menu.
Command cmd = new Command() {
public void execute() {
Window.alert("You selected a menu item!");
}
};
MenuItem firstMenuItem = new MenuItem("First", cmd);
MenuItem secondMenuItem = new MenuItem("Second", cmd);
MenuItem thirdMenuItem = new MenuItem("Third", cmd);

ourMenu.addItem(firstMenuItem);
ourMenu.addItem(secondMenuItem);
ourMenu.addItem(thirdMenuItem);
baseMenu.addItem("Our Menu", ourMenu);
Then we attach our menu to our panel and voila.
baseMenu.addItem("Our Menu", ourMenu);
Just hit F5 on the hosted browser window and you will see your menu. If you want your menu to be colorful and sweet you must use some CSS. Open MyApplication.html and change style tag to look like:


Now you must have nice colorful menu to have fun with.




I am not pro with CSS so I recommend you to learn from somewhere else how to make it look better.
This will be for today. Expect tomorrow to learn how to use some other fun components. ;)



Popular Posts