Czech version
logolink

< Back to the list of lessons

JavaScript and jQuery

PHPContent of the lesson:

  • Using jQuery
  • Selectors
  • Practical Example

Using jQuery

When creating websites you might want to get more than static HTML code written in files or dynamically generated by a programming language. Image effects, text effects, enlarging images, fading in or out, checking forms and much more can improve the impression of a website.

JavaScript is usually used for these effects. When working with JavaScript, you should remember that different browsers are not fully compatible and your effects might not run in all of them properly. However, you can use several JavaScript frameworks which make the work much easier and solve incompatibility perfectly. A difficult effect then can be easily created.

One of those frameworks is jQuery which can be downloaded from the official page for free. There are two variants - minified and uncompressed. They are different in size of files but their functionality is the same. The version uncompressed is larger and the source code is well-arranged. Using it is suitable in case that you want to make changes directly inside the jQuery framework.

HTML code needed for loading the library

<script type="application/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="application/javascript">
$(document).ready(function(){
//insert code here - it is run once the page is ready
});
</script>

As you can see from the example we added a link to the jQuery framework into the source code (in our case the line <script type="application/javascript" src="js/jquery-1.4.2.min.js"></script> - used path to the file can differ according to the variant of jQuery which we have chosen and also to the location of this file) and Javascript with function $(document).ready. This function contains code which will be executed in our page. All commands inside this function will be executed after the page is loaded.

Selectors

The strongest weapon of jQuery is that it can work with object model of document (DOM). There are several types of selectors and you can find your element using them:

  • XPath
  • CSS
  • Special selectors

CSS selectors will interest us the most. Using them we can search elements inside HTML document as we do in CSS styles.

The following sample demonstrates how can we hide (function hide()) all blocks (p) after clicking on a button (id="tlacitko").

Sample of using selectors
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/javascript" src="jquery-1.5.js"></script>
<script type="application/javascript">
$(document).ready(function(){
	$('#tlacitko').click(
		function(){
			$('p').hide();
		}
	);
});
</script>
<title>Ukázka použití JQuery</title>
</head>
<body>
<p>Ukázka použití JQuery</p>
<input type="button" id="tlacitko" value="Hide text" />
</body>
</html>    

The functionality of this script is simple. You can see a button inside the page with identifier id="tlacitko". Using jQuery we assigned the event click (function which will be done after clicking on that button) to this button. A new function is defined inside this event and contains only one operation - the command hide() which will be used for all paragraphs, that means it will hide these paragraphs ($('p').hide();).

We can adjust our sample. The function hide() which hides objects in the page is replaced by the function toggle(). This function displays or hides an object according to the fact whether it is or is not visible. The adjusted page can be seen in the following source code:

Sample of using selectors
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/javascript" src="jquery-1.5.js"></script>
<script type="application/javascript">
$(document).ready(function(){
	$('#tlacitko').click(
		function(){
			$('p').toggle();
		}
	);
});
</script>
<title>Ukázka použití JQuery</title>
</head>
<body>
<p>Ukázka použití JQuery</p>
<input type="button" id="tlacitko" value="Show / hide text" />
</body>
</html>    

We can even more extend our sample. In case you wanted to show or hide only one concrete paragraph you would have to assign it with the value id which will be referred in jQuery.

Sample of using selectors
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/javascript" src="jquery-1.5.js"></script>
<script type="application/javascript">
$(document).ready(function(){
	$('#tlacitko').click(
		function(){
			$('p').toggle();
		}
	);
    
    $('#tlacitko2').click(
		function(){
			$('#varovani').toggle();
		}
	);
});
</script>
<title>Ukázka použití JQuery</title>
</head>
<body>
<p>Ukázka použití JQuery</p>
<p id="varovani">Warning</p>
<input type="button" id="tlacitko" value="Show / hide text" />
<input type="button" id="tlacitko2" value="Show / hide warning" />
</body>
</html>    

The last sample shows using selectors for CSS classes (class). This way can be used to access several different objects inside a page (objects with the same class values).

Sample of using selectors
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/javascript" src="jquery-1.5.js"></script>
<script type="application/javascript">
$(document).ready(function(){
	$('#tlacitko').click(
		function(){
			$('p').toggle();
		}
	);
    
    $('#tlacitko2').click(
		function(){
			$('#varovani').toggle();
		}
	);
    
        $('#tlacitko3').click(
		function(){
			$('p.napoveda').toggle();
		}
	);
});
</script>
<title>Ukázka použití JQuery</title>
</head>
<body>
<p class="napoveda">help 1</p>
<p>Ukázka použití JQuery</p>
<p class="napoveda">help 2</p>
<p id="varovani">Warning</p>
<p class="napoveda">help 3</p>
<input type="button" id="tlacitko" value="Show / hide text" />
<input type="button" id="tlacitko2" value="Show / hide warning" />
<input type="button" id="tlacitko3" value="Show / hide help" />
</body>
</html>    

Individual Task

Download the file ukol1.html and using jQuery create a script which will do the following steps:

  1. Hide all answers after loading page
  2. Show the corresponding answer after inserting the correct password and clicking on the button.

You can use these links for help: Selektory, funkce Parent(), Události (Events).

Solution of the Task

Save the file ukol1.html into the computer and open it in a HTML editor. You will find out that this document was prepared for you and there is a javascript function $(document).ready where we will only write script which will be executed after entering the right password and clicking on the button.

At first you have to hide all answers. All answers are placed into p blocks which are assigned to the CSS class odpoved. Add the following lines to the script (highlighted in bold).

Solution of the task - hiding the answers
<script src="../js/jquery-1.4.2.min.js" type="text/javascript"></script><script type="text/javascript">
$(document).ready(function(){
	$('.odpoved').hide();
});
</script>

Then the answer should be revealed in case of a correct answer.

Solution of the task - completing
<script src="../js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
	$('.odpoved').hide();
    
    	$('input[type="submit"]').click(function() {
		if ($('input[type="text"]',$(this).parent('form')).val()  == "heslo")
		{
			$('.odpoved',$(this).parent('form').parent('.polozka')).show();
			$(this).parent('form').hide();
		}
		return false;
	});
});
</script>

To prevent creating a single function for every button separately (you can theoretically add unlimited number of questions), we have to create a function which will be assigned to all buttons in the page. This can be done by adding the event click to all objects of type input which have the property type set to the value submit ( (command: $('input[type="submit"]').click(function() { ... });).

When executing this event the program finds out that a correct password was entered. In our case it compares the entered text with the string "heslo". The comparison is done by the if function. We can access the value inside text array by addressing the object input which has assigned its type parameter with the value text. However, if you used this solution, you would face one problem. There are many objects of these criteria in the page. Javascript cannot know which one should be accessed. Because of that, identification of an object will contain one additional parameter. This will be parent('form'). It informs the javascript that the object which should be accessed is a part of form which is parent for the button. To get the text which is written in the text area, we will use the function val(). The final header of the if condition will look like the following code: if ($('input[type="text"]',$(this).parent('form')).val() == "heslo"). The parameter this which is used refers to the button which was clicked.

In case that the if condition is valid the answer is shown. It is identified with the css class odpoved. But there are also more objects inside the page so we also have to identify it closer using the function parent. This function will be used twice because we need to get to the block polozka which is parent for the form which is parent for our button. And our block odpoved which should be shown is located inside the block polozka. The command which will show it is: $('.odpoved',$(this).parent('form').parent('.polozka')).show();. Of course we also have to hide the form. The form is parent for our button so we can refer it using the following way: $(this).parent('form').hide();.

The last part of handling the click event is the row return false;. This only sends the return value false because we do not want the form to be processed at server which would result into refreshing the page into the beginning state. This procedure is common at buttons of type submit.

Practical Example

We will create a script which will display a description of photo using an interesting effect.

náhled efektu

We have to decide how to write our data. You should realize that JavaScript might not be available in a browser so you should suggest a solution which can be used in both variants.

Structure of HTML code of one photo
<div class="obrazek">
<img src="images/Lighthouse.jpg" alt="Maják" />
<div class="popisek">Maják a západ slunce</div>
</div>

This structure allows us to display the photo and its description in case that JavaScript is turned off. The photo and the description belong to the same element so it is clear that these two details belong together.

You can use any classes but you should use such names which are logical. The main div has class "obrazek" - it contains image and its description. The div with description has class "popisek". You cannot use identifiers because you want to create a universal effect for any number of images.

The next step is adding CSS styles. We want the description to be placed inside gray block under the image. You can use similar CSS rules as in the following code:

CSS styles
<style type="text/css">
.obrazek{
            float: left;
            margin-left: 20px;
            }.popisek{
            background:  #333333;
            color: #FFFFFF;
            padding: 10px;
            height: 75px;
            }
</style>

The last step is adding our effect to the description. We want to display the description after placing mouse cursor over the image and to hide the description after leaving the image. In the documentation of jQuery inside the list of events you can find hover(). Hover() is a function which can operate placing cursor on place as well as leaving the place. This should be the event we wanted.

You can find several interesting effects in the documentation, for example fadeTo() which we will use to show the description of image (you can set transparency) and fadeOut() which we will use to hide the description.

Final JavaScript
<script type="application/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="application/javascript">
$(document).ready(function(){
	$('.popisek').hide();
	$('.popisek').css("position", "relative");
	$('.popisek').css("margin-top", "-95px");
	$('.obrazek').hover(
		function(){
			$('.popisek', this).fadeTo('slow', 0.8);
		},
		function(){
		   	$('.popisek', this).fadeOut();
		}
	);
});
</script>

Additional Texts

Links

Questions

  1. How can you choose an element of page in jQuery?
  2. Which JavaScript events do you know?
webdesign, xhtml, css, php - Mgr. Michal Mikláš