jQuery Coding Fundamentals Series (#1): A guide to the basics of jQuery

in #utopian-io7 years ago (edited)

Introduction

Java Libraries such as JQuery make it simple to use from Java Script highlights. They are quick and more good with programs than Java Script and are helpful for apprentices and competent to get associate with server side dialect as php, however it is customer side dialect. JQuery is a special one that has diverse releases.

What Will I Learn?

  • Start simple Programming in Java
  • Select the Page Elements
  • Handling Events - Adding Effects
  • Add or Remove a Class (Style)
  • Dealing More with Classes
  • Style Changing with Mouse

Requirements

  • Knowledge of basic HTML
  • Knowledge of basic Java Script

Difficulty

  • Basic

The First Steps

Let’s create an html page before anything. Note that you should save your page in ‘.htm’ or ‘.html’ to get able for using from all features of JQuery. Here is sample of an html page:

<html>

<head>

<title>New JQuery Page</title>

<style>

 

</style>

</head>

 

<body>

<p>This is my first JQuery Page!</p>

<p>See It...</p>

</body>

 </html>     

Two important parts from html codes used to put JQuery codes inside them are style and body sections. In body part our main JQuery codes take place and in style part we define styles which we add to our html objects with JQuery language.

Now we must connect our page to JQuery library file in the body part. Save a copy of JQuery beside your htm file and rename it to 'jquery.js' or you can use from its online source. Look at below to understand how:

<body>

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

<script type="text/javascript">

 

</script>

</body>

OR…

<body>

<script type="text/javascript"

                     src="http://code.jquery.com/jquery-1.5.1.min.js"></script>

<script type="text/javascript">

 

</script>

</body>

OK, now our JQuery page is ready! What do we have done? First we have opened script tag and set it to the language which we use (Java Script); then we’ve defined our source (jquery.js) file.

At first part of the above table, JQuery file is beside our html file and at the second, the source is from its main site. We’ve closed first script tag and start new one to put our codes between them.


Start a Programming in JQuery

Anything you want to call in JQuery must have '$' sign at first and its name must come inside the parentheses. For example if you want to write something about current document (or current page) you should write like:

$(document)

We call anything that can come in this form, an ‘Object’. Objects have different events and properties, you must define what you want exactly by putting a dot after the object you called and writing the specified event or property; for example if we want to get access to time that the document gets ready (all of its details are completely loaded at this time) we'll write this:

$(document).ready

This is an event and we want to do some thing at this time; It means that we want to run some codes after the document gets ready. By opening a parenthesis we have a place to put our codes to get ran in this time. But parentheses alone is not enough; you must write 'function(){ . . . }' in it.

It shows that you have some operations at ready time and the operations will come between two brackets. then we must close the parenthesis of ready event after the brace at end. Semicolons are always needed in javascript at the end of each line, but here is not necessary! By combining what we have learnt up to now, we should have something like this:

<body>

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

<script type="text/javascript">

        $(document).ready(function() {

         });

</script>

</body>

The empty space between two braces ' { } ' is the place to put our codes which will ran after complete loading of current doccument.


Select the Page Elements I

One of important JQuery features is to manage elements in the page and change their settings and appearance. To do this we must have access to them. A dollar sign with parentheses always specify elements and objects. Here we can select an object in different ways:

  • $("type"): Selects all elements from specified type in the page.

            Examples:
    
                $("a"): Selects all anchors.
    
                $("p"): Selects all paragraphs.
    
  • $("#ID"): Selects the element with specified ID (it is possible to add an ID for each element in the page such as an image or a table cell).
    Examples:

                 $("#rImage"): Selects an element with 'rImage' ID.
    
                 $("#tblTD"): Selects an element with  ’tblTD' ID.
    
  • $(".Class"): Selects all elements that have specified Class (Classes can be defined inside '' part at the head section).

  • $("type.Class"): Selects all elements that have specified Class from specified type.

  • $("type#ID"): Selects an object which has specified ID from specified type (You may have same IDs for different types, use it to avoid confliction).
    Examples:

                  $("div#n1"): Selects an element with 'n1' ID from 'div' type.
    
                  $("a#mySite"): Selects an anchor with 'mysite' ID.
    

We can have also more complex selectors with more details:

  • $("input[type=sth]"): Selects all inputs that have specified type.
    Examples:

                  $("input[type=text]"): Selects all text-inputs.
    
  • $("type:first(last)"): Selects the first (last) element from specified type
    Examples:

                  $("div:first"): Selects the first div.
    

Select the Page Elements II

Some other selectors are listed below:

  • $("type:odd(even)"): Selects even (odd) elements of the type. Indexes start from zero; so the first, third, ... elements (indexes: 0, 2, …) are odd and the second, forth, ... elements (indexes: 1, 3, …) are even elements.
    Examples:

                  $("p:odd"): Selects all odd paragraphs.
    
                  $("tr:even"): Selects all even table lines.
    
  • $("list li:first(last)") :Selects the first (last) line from the first (last) list in the current page.
    Examples:

                  $("ol li:last"): Selects the line of the last ordered list.
    

And the other kinds of selectors are illustrated below; you can add similar elements in these styles:

  • $(":radio"): Selects all radios in the page.
  • $(":checked"): Selects all radios or checkboxes which are checked in the page initially (changes after the load of the page by visitors aren't important).
  • $(":animated"): Selects all animated elements in the page (We discuss later about how to animate an element).
  • $(":header"): Selects all headers (h1,h2,... tags).
  • $("[value='sth']"): Select all elements with specified value (ex. buttons, text, ...)
  • $("[href!='somewhere']"): Select all anchors that their links aren't the specified link.
  • $("p,.cl,#k1"): Select all paragraphs, all elemnts with 'cl' class and the elemnt with 'k1' id.
  • $("table:visible(hidden)"): Select all visible (invisible) tables.

After selecting an object, we must specify what we want from it; maybe a change is needed, the current value of it should get read or etc.


Handling Events - Adding Effects

As before we must set when our codes must be ran. Although all codes will run at document ready time but we can classify it by adding another event below this event. For example we may want to run a code when an anchor is clicked. The following example shows it:

<body>

<ahref="Http://www.javascriptfreecode.com">

           <font size="3">Http://www.javascriptfreecode.com</font></a><p>

<a href="Http://www.phpfreecode.com">

           <font size="3">Http://www.phpfreecode.com</font></a><p>

<a href="Http://www.htmlfreecode.com" >

           <font size="3">Http://www.htmlfreecode.com</font></a><p>

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

<script type="text/javascript">

        $(document).ready(function() {

              $("a").click(function(){

                                alert("Thanks for visiting!");

              });

});

</script>

</body>

Now we have place to write codes which will ran when you click on each anchor in the page. alert is a function which shows a message box. The text in parentheses between two quotes is the message content. Another event handler is ‘mouseover' . Its codes will be ran when you point the cursor on it; so it becomes something like this:

<body>

 <div><font color="#00FF00">Hello</font></div>

<div><font size="5" color="#FF0000">How are you there?</font></div>

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

<script type="text/javascript">

        $(document).ready(function() {

                $("div").mouseover(function(){

                           alert("Thanks for visiting!");

                });

});

</script>

</body>

Output
Hello

How are you there?

Here we’ve replaced anchor with ‘div'. When you point to a ‘div', a message box will appear.

We have listed more event handlers with their definitions in the next lesson…


More Events to Handle

You are familiar with events from previous lessons. Now just replace following events with ones that we had in the previous examples and use their benefits:

  • blur(): Write codes that must get ran when an element loses focus or gets left, below this event (for example a textbox is left and another element, by the Tab key or clicking, is selected).
  • change(): This event is triggered if you change current state of an element (ex: changing a text box text or select an option from a list) and leave it by clicking out or pressing the Tab key (the two last operations are needed just for text boxes).
  • dblclick(): As it is obvious, it is for handling double-click event.
  • error(): The codes in this handler will be ran when an element faces to an error (for example if a specified picture isn’t loaded)
  • focus(): The codes works when an element gets focus.
  • focusin(): It is similar with focus().
  • focusout: It is similar with blur().
  • hover(): In fact it is two handler in one! It is triggered one when a pointer comes to an element area and again when it leaves the area.
  • keydown(): The codes works when a key is hold down on an element and it is continues getting ran again and again, while the key is held down.
  • keyup(): This event will be triggered once, when you leave a key from holding on an element.
  • keypress(): This event will be triggered when a key is pressed on an element and the code continues getting ran again and again, while the key is held down.

The unknown point here is to find what the pressed key is, in the three introduced last events.


Which Key is Pressed?

To use key handlers we must use another java library with the name ‘event.js'. For understanding what the characteristic of key which is used by a visitor is, we need to add something to our handler functions that we introduce them step by step.

The function that we had after an event, didn't have any parameter for getting or sending data, between the parentheses; Here ‘event' argument play an important role for us! It contains the specifications of the key used; so our main discussion here is on this argument that comes between the parentheses. The structure of our script changes to the following codes, up to now:

<body>

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

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

<script type="text/javascript">

        $(document).ready(function() {

               $('#target').keydown(function(event) {

 

               });

         });

</script>

</body>

Now we can reach to our purpose by extracting ‘event' argument. You can see everything exist in it with general printing ( ‘$.print(event)’ ); it will print the result after the loaded page elements. By adding a dot after ‘event' you can have access to its specifications; add a word ‘keycode' or ‘which' to read the pressed key code. The following example shows what to do:

<body>

<p><input type="text" name="tbox" size="20" id='target'></p>

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

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

<script type="text/javascript">

  $(document).ready(function() {

        $('#target').keydown(function(event) {

               alert(event.which);

               $.print(event.which)

        });

   });

</script>

</body>

The procedure for keypress or keyup is the same.


Add or Remove a Class (Style)

Before continuing events and their handling, let's know about some java effects to match them with events we learned before; other events will be illustrated later.

Different ways exist to add an effect to an html element. The one that we want to introduce first is adding a predefined style to an existing element. First we make html page elements with blank spaces for styles and JQuery codes:

<head>

<style>

 

</style>

</head>

 

<body>

<p><input id='divd' type="button" value="Add Style" name="divd">

<input id='divr' type="button" value="Remove Style" name="divr"></p>

<p><div style="position: absolute; width: 100px; height: 100px; z-index: 1; " id="div1">

Hello There</div></p>

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

<script type="text/javascript">

         $(document).ready(function() {

 

         });

</script>

</body>

The styles are defined between ‘<style>...</style>’ tags in the head part of the page, like this:

<style>

    .divStyle {padding:10 10 10 10; background-color: #99FFCC;}

</style>

As you may know from html tutorial, style part is used to define appearance of an element whether by its type name to get applied on all of its objects (ex. div.stylename), or not ( .stylename) to get applied later.

The styles here can get added to an element, if they aren't set before in element main html definition or in the style part between the head tags. For example if you have ‘padding' in html main definition of an element, ‘divStyle' that is defined above has no effect when get added to a div by JQuery Codes.

What should we write to use this feature of JQuery? First we must select an event handler, for example a button when gets clicked. ‘divd' is our button name and as we said ‘#' sign is essential here (to select an element with specified ID). Then we select a single or group of elements wanted to defined a new style:

$(document).ready(function() {

    $('#divd').click(function(){

        $("div").addClass("divStyle");

    });

});

By the middle line we've added ‘divStyle' to all divs exist in the page. We can also remove the added style by ‘removeClass' code:

$(document).ready(function() {

    $('#divr').click(function(){

        $("div").removeClass("divStyle");

    });

});

So our whole script must be:

<head>

<style>

    .divStyle {padding:10 10 10 10; background-color: #99FFCC;}

</style>

 

</head>

 

<body>

<p><input id='divd' type="button" value="Add Style" name="divd">

<input id='divr' type="button" value="Remove Style" name="divr"></p>

<p>

<div  style="" id="div1">

Hello There</div></p>

 

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

<script type="text/javascript">

 $(document).ready(function() {

        $('#divd').click(function(){

        $("div").addClass("divStyle");

    });

 

    $('#divr').click(function(){

        $("div").removeClass("divStyle");

    });

});

 

</script>

</body>

Notice that JQuery codes may not work correctly if you don't attend to their case sensitivity (Capital Letters and small Ones).


Dealing More with Classes

We've learned about adding and removing classes in the previous lesson in separate buttons; but what should we do if we want to merge these two buttons to one? In this case our button will add a class if it doesn't exist and remove it, if it exists in the elements styles. ‘hasClass()’ function aware us whether it exists or not:

$(document).ready(function() {

    $(#divd').click(function(){

        if ($("div").hasClass("divStyle"))

            $("div").removeClass("divStyle");

        else

            $("div").addClass("divStyle");

        });

});

Or a shortcut way does it automatically for us; that is ‘toggleClass()' function:


$(document).ready(function() {

   $('#divd').click(function(){

       $("div").toggleClass("divStyle");

   });

});

Notice that all divs are selected here and the effect of above script is done on all of them. More event handlers are introduced below:

  • mouseenter() or mouseover(): These events will be handled when the mouse pointer enters in the element area.
  • mouseleave() or mouseout(): These are for when the mouse pointer goes out from element area.
  • mousedown(): This will be triggered when one mouse key is held.
  • mouseup(): It is for when the mouse held key is released.
  • mousemove(): The codes placed below this function works when the mouse pointer is moved on the element.

You can also edit existing styles by ‘css()’ function.


Style Changing with Mouse (example)

Let's begin with a full example code about changing styles by mouse pointer. You can copy and paste it in a new html page or see its effect in the right side of the table; we'll introduce what happens later in this lesson:

<body>

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

<script type="text/javascript">

        $(document).ready(function() {

                $('td').mouseover(function(){

                        $(this).css('border-style', 'solid');

                });

                $('td').mouseout(function(){

                        $(this).css('border-style', 'none');

                });

                $('td').mousedown(function(){

                        $(this).css('border-width', '5');

                        $(this).css('border-color', 'red');

                });

                $('td').mouseup(function(){

                        $(this).css('border-width', '2');

                        $(this).css('border-color', 'windowtext');

                });

        });

</script>

 

<table border="1" width="100%" style="border-color:windowtext;"

 cellspacing="3" bordercolor=black bordercolordark =black

 bordercolorlight=black>

<tr>

<td  style="border-style: none; border-width:2; border-color:black"

bgcolor="#DFDFDF" >

<p align="center">Click here 1</td>

<td  style="border-style: none; border-width:2; border-color:black"

bgcolor="#DFDFDF">

<p align="center">Click here 2</td>

</tr>

<tr>

<td  style="border-style: none; border-width:2; border-color:black"

bgcolor="#DFDFDF">

<p align="center">Click here 3</td>

<td  style="border-style: none; border-width:2; border-color:black"

bgcolor="#DFDFDF">

<p align="center">Click here 4</td>

</tr>

</table>

</body>

The output will look something below;

Click here 1Click here 2
Click here 3Click here 4

Put your mouse pointer on the gray table at right side of above example. The table cells have no border; when you point to them, a border will be shown around the cell.

When you leave the cell, the border will disappear. Click on a cell and keep the mouse key pressed; the border becomes thicker and gets red; Now leave it; the cell returns to its previous style.

The code of this example has two main parts: an HTML part and a JQuery part. The HTML part is after the JQuery one. The only thing that is important for us in this lesson is ‘style' section of each table cell ‘<td style="...">.

Three cell settings exist here; we’ve set the cell border style to none; so every cell doesn't have any border. The border width or border thickness specifies the border thickness if it isn’t set to none. A similar thing is true about the cell border color.

In the scripting part, when the document gets ready, four mouse handlers become active. We've told what the work of each handler is, in the previous lesson.

They operate for each <td> cell in the page. ‘$(this)’ returns the <td> cell which the mouse pointer is now on it; so we change its style depends on what the mouse done. ‘.css' code has two input parameters, the first one is the style name and the second one is its value. The value is set for the specified style with this function.


Conclusion

I hope you had fun with this tutorial. We have done our best to make it as simple as we can. JQuery is a quick and brief JavaScript Library made by John Resig in 2006 with a decent maxim: "Write less, accomplish more". jQuery rearranges HTML report navigating, occasion taking care of, quickening. jQuery is a JavaScript toolbox intended to disentangle different undertakings by composing less code.

You'll be unable to discover a site that utilizes JavaScript without additionally utilizing jQuery. It has turned into a vital apparatus in present-day web improvement, and as it should be. You must have figured out how it makes programming so significantly less demanding, and we've scarcely touched the most superficial layer! jQuery is all round and excellent.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

You have a minor misspelling in the following sentence:

Knowlege of basic HTML.
It should be knowledge instead of knowlege.

Thanks i will make corrections right away.

Congratulations @henrieta! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You made your First Comment

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Do not miss the last announcement from @steemitboard!

Your contribution cannot be approved because it does not follow the Utopian Rules.

  • Submissions focused on the use of functions that are already well documented in the project documentation will be rejected. jQuery

My sugestion:

  • Try to make a tutorial that is useful for the open source community, in which there isn't much content on this subject on the internet and that is interesting for our community. Thank you.

You can contact us on Discord.
[utopian-moderator]

Congratulations @henrieta! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Coin Marketplace

STEEM 0.22
TRX 0.27
JST 0.041
BTC 104021.29
ETH 3869.26
SBD 3.33