Master JQuery Today: Lesson4, how to select elements

In this fourth JQuery lesson, I will be discussing how to generate a response from selected elements defined in the JQuery function.

$(document).ready()

The most common JQuery function is the .ready() method that is used to specify a function to execute after a page loads.

JQuery Ready Function
JQuery Ready Function

In the above example, the $(document).ready(function) executes the function (alert) when the page loads. The alert message is displayed (“Ready function on the go!”).

Here’s the code: JQuery Ready Function

$(“div tag”)

JQuery Function
JQuery Function: Add a Tag

In the above example, the JQuery function is getlevels() and it calls an alert method, where the $(“p span”).length accesses all the <span> elements inside the <p> tag and counts the number (length) of all the span elements (as displayed in the example).

Here’s the code: JQuery Ready Function Div-Tag

$(“div tag”) is different from $(“div>tag”)

There is a difference between the $(“div tag”) and $(“div>tag”): the first one accesses all the top and sub-child elements, while the second one only the top elements. In the first example, the first alert $(“div tag”) counts all the <span> elements: the result is 3 as there are two top <span> levels and one <span> sub-level. In the second case, the $(“div>tag”) counts only the top <span> elements and ignores the sub-children. Therefore, the final result is 2.

JQuery Div Tag
JQuery Function Div-Tag
JQuery Function Div greater than Tag
JQuery Function Div>Tag

Here’s the code: JQuery Div and Tag

$(“tag:contains(text)”)

JQuery Contains
JQuery Contains Method

In the above example, the function checkContent() defines an alert method which calls $(“tag:contains(‘text’)”). In this case the tag is a <p> <span>, followed by contains where the text is equal to ‘Sheldon Cooper‘. In the body, the <div> calls the checkContent function by clicking on the text “Click Here” (onclick method). Some style was also added: the cursor turns into a pointer and the text color is red. To find the selected text, we need to insert it into <p> and <span> dividers. By clicking on “Click Here“, an alert message shows the text that contains ‘Sheldon Cooper‘.

Here’s the code: JQuery Contains Method

$(“tag[attribute=value]”)

The $(“tag[attribute]”) can access a tag with a specific attribute.

JQuery Tag Attribute
JQuery Tag Attribute

In the above example, the function getHeadline() defines an alert method which calls $(“tag[attribute]”). In this case the tag is a <div>, whose attribute is id=Sheldon. In the body, the <onclick> method calls the getHeadline function by clicking on the button “Click Here“. In the body there are three <div> and each is defined by a unique id. By clicking on “Click Here” button, an alert message shows the text that is contained in the <div id=Sheldon>.

Here’s the code: JQuery Tag-Attribute

$(“#id”).is(‘tag’)

The $(“#id”).is(‘tag’) tests if an element with a defined id is a tag element.

JQuery Check Element Tag
JQuery Check Element Tag

In the above example, the function checkelementTag() defines an alert method which returns true if the element with the ID “#divId” is a <div> element. In the body, the <onclick> method calls the checkelementTag() function by clicking on the button “Click Here“. By clicking, an alert message shows “true” as the text is contained in the <div id=divId>. If the condition was not met, it would return False.

Here’s the code: JQuery Check Element Tag

$(“tag:eq(5)”)

The $(“tag:eq(5)”) access a tag with an index number equal “5”. The method :eq() is used to select an element with a specific index number.

JQuery Check Index Method
JQuery Check Index Method

In the above example, the function checkelementIndex() defines an alert method which returns true if it can find a <div> element at position 5 (index number starts from zero!). In the body, the <onclick> method calls the checkelementIndex() function by clicking on the button “Click Here“. By clicking, an alert message shows the text contained in the <div > at position 5.

Here’s the code: JQuery Check Tag Index Number

$(“input:checked”)

The $(“input:checked”) method access an input tag that has been checked. This method is generally used with radio buttons and checkboxes.

JQuery Input Checked Method
JQuery Input Checked Method

In the above example, the function getCheckedCount() access an input tag that has been checked and count how many tags have been selected. In the body, the <onclick> method calls the getCheckedCount() function by clicking on the button “Click Here“. By clicking, an alert message shows the number (or length) of selected tags (in this case, 2).

Here’s the code: JQuery Input Checked Method

$(“select option:selected”)

The $(“select option:selected”) method accesses a “select” tag with a selected option.

JQuery Select Option Selected Method
JQuery Select Option: Selected Method

In the above example, the function getSelectedValue() access an input tag that has been checked shows its content. In the body, the <onclick> method calls the getSelectedValue() function by clicking on the button “Click Here“. By clicking, an alert message shows the content (or text) of selected tags (in this case, Penny).

Here’s the code: JQuery Select Option Selected Method

Learn JQuery Today: Lesson3, Slide, Insert and Check methods

In this third JQuery tutorial, I will be focusing on how to slide elements up and down (it is similar to hide and show), Insert new elements and finally check elements conditions (such as gender, terms and conditions and so on).

1. Slide element up and down

JQuery Slide Up
JQuery Slide Up Method

The function is called SlideUp and refers to a divTest which calls a slideUp method. In the body, there is a div that calls the slideUp function when a user clicks (onclick method) on the “Click Here” text. In addition, some style has been added so that when a user mouses over, the cursor turns into a pointing hand. (style=”cursor: pointer;”). The function is then applied to a div whose id=divTest. In this case, it is applied to the text “This thing slides up…” as it is contained inside the divTest. Some style has also been applied, the background-color (:blue), the font color (:white) and the size of the background (margin-top, width and height).

JQuery Down Method
JQuery Slide Down Method

This example shows how calling the JQuery slideDown() method allows a text contained in a divTest to appear when a user clicks some text. This JQuery function shows only few changes compared to the slideUp() method described above. This change is optional, as the function could be called anything we like! As it has been called slideDown(), the onclick method needs to call a slideDown() function now. The text inside the div whose id=divTest has been changed from “This thing slides up…” to “This thing slides down…“. The text is optional, you can insert anything! Even the picture of a big fluffy cat holding a light saber! The final change is adding some necessary style, that is a “display: none;” option into the our divTest. This is required as we want the text defined by blue background to appear when people click on the text “Click Here“.

Here’s the code: JQuery Slide UP and DOWN Method

2. Insert Element

In JQuery there are two methods: insertAfter() and after() to insert html content or text after the matching elements.

JQuery Insert Methods
JQuery Insert Methods

 

In the above example we have defined a function called insertAfterHtml() which calls two JQuery methods. an .insertAfter() and .after(). In both cases, the method inserts some text after the tag whose id=divInsertAfter. The only difference is in the syntax.

Here’s the code: JQuery Insert Element

3. Check Element Conditions

The JQuery method “is()“checks if an element matches a given conditions and then returning a True or False.

JQuery Check Element Conditions
JQuery Check Element Conditions

The JQuery function is called checkGender and uses the method .is(“;checked”) to test if a tag (input type=”radio”) called either #checkFemale or #checkMale has been selected. The “Click Here” text calls the checkGender() function which displays the Alert() depending on the selection which is based on the tag id, either checkFemale or checkMale.

Here’s the code: JQuery Check Element Condition

How to master JQuery today: Lesson2, Show and Hide

Today I will be discussing how to generate a JQuery function with some easy examples. This post follows JQuery Lesson1 which introduces JQuery and how to add CSS style using this computer language.

1. How to Add a Class: the add() Method

$(“selector”).addClass()

Jquery Function to Change Color
JQuery Function: Change Color

In the above example the JQuery function aims to change the style of <p> elements into red and italic style. The function is called changeColor() and as explained in the previous lesson can be named anything we want. The $(“selector”) is a <p> element and therefore it becomes $(‘p’). The JQuery .addClass() becomes .addClass(“redClass”) as it calls a class called “redClass” which add style to a specified text (<p>). In the <body> we need to call the JQuery function just specified. We add a button (input type=”button”) that allows users to execute the function on the click of a button. The onclick=”changeColor()” executes the “changeColor()” function when clicking the button.

Here’s the code:

<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

function changeColor(){
 $('p').addClass("redClass");
 }

<style>
.redClass{
color: red; font-style: italic;
}
</style>
</head>
<body>

<p>Learn JQuery today!</p>
<p>It is very easy!</p>
<p>Just follow this tutorial.</p>

<form>
<input type="button" value="Change Color" onclick="changeColor()"></input>
</form>

</body>
</html>

2. Add and Remove a Class: The toggle() Method

The ToggleClass() is a JQuery method used to add or remove classes. If the class is present, it will be removed, if it is absent, it will be added. If we consider the above example, we could obtain the same results by changing a simple line of code: from .addClass() to toggleClass.

Here’s the code:

<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

function changeColor(){
 $('p').toggleClass("redClass");
 }

<style>
.redClass{
color: red; font-style: italic;
}
</style>
</head>
<body>

<p>Learn JQuery today!</p>
<p>It is very easy!</p>
<p>Just follow this tutorial.</p>

<form>
<input type="button" value="Change Color" onclick="changeColor()"></input>
</form>

</body>
</html>

3. The size of an Element: The size() Method

The size() method returns the number of elements that matched. The JQuery size() method:

$(“Tag”).size()

JQuery defines the size of an element
JQuery defines the size of an element

As in previous examples, we give the JQuery function a chosen name, such as getSize() followed by the method alert that we described in the previous post (Lesson1). The alert method contains the phrase “the size of li is”, the $(“li”)  as $(“selector”) and the size() method. In the <body> we have 3 <li> elements and a <form> that contains an <input type=”button> which, if clicked, generates a pop-up (alert) that states how many <li> element the <body> contains as the onclick=”getSize()” executes the “getSize()” JQuery function when clicking “Get li Size“.

Here’s the code:

<!DOCTYPE html>
<html>
<head>
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

function getSize(){
 alert("the size of li is:"+$("li").size());
 }

</head>
<body>

<ul>
<li>Homepage</li>
<li>Items</li>
<li>Blog</li>
</ul>

<form>
<input type="button" value="Get li Size" onclick="getSize()"></input>
</form>

</body>
</html>

4. How to show hidden elements: the show() method

The show() method is used to show hidden elements when selected, for instance when clicking to some text or a button.

$(“selector”).show()

JQuery hidden text method
JQuery how to show hidden text

In the above example we want to show some text when users click on some text. As before we define a JQuery function as showText() and we use the method $(“selector”).show() where the selector is a div tag named Test (“#divTest”). In the body we call the JQuery function (“showText”) when clicked over (onclick) the “click here” text. To display the hidden text we call a div whose id is “divTest“. To make things even more visible we give the hidden text some style, a green background and a white font style.

Here’s the code: JQuery Show Function

5. How to hide selected elements: the hide() method

The hide() method is used to hide content for the matching element from the <body>.

$(“selector”).hide()

By simply changing the previous code from .show() to hide(), the JQuery function will turn from showing to hiding content on the click of a button! To make things a little clearer, we can also rename the function hideText. Therefore, the onclick must now call a “hideText” function instead. The last bit of code that needs some modification is the div element style, which does not need  the “display: none;” option anymore.

Here’s the code: JQuery Hide Function

6. How to hide and show: the toggle() Method

The toggle() method allow users to switch between hide and show for the matching element.

$(“selector”).toggle()

By simply changing the previous code from .hide() to toggle(), the JQuery function will turn from hiding content to showing/hiding content on the click of a button! To make things a little clearer, we can also rename the function toggleText. Therefore, the onclick must now call a “toggleText” function instead. Now, the first click on “Click here” will hide (bottom-right) the text, while the second click will show the text again (top-right), and so on.

JQuery Toggle
JQuery Toggle, Show and Hide

 

Here’s the code: JQuery Toggle Function

How to master Jquery with this easy tutorial: Lesson1, the basic

Learning a computer language is something we always promise ourselves we will be doing soon. Maybe we have promised ourselves to sign up to an online course, follow a tutorial on YouTube or bring out that old tech book.

Unfortunately, most of the times the enrolling date passes, YouTube is visited for more entertaining purposes and that old tech book is still relegated to the shelf. We have all done it, we have all being guilty at a time or another.

Today I will try to tech you how to start coding in JQuery using practical examples. To begin with let’s define what JQuery is and what the advantages are (I promise I will try to keep the technical jargon to the minimum):

JQuery is a client side-scripting library of JavaScript. Its main advantages are:

  1. It is compatible with various browsers
  2. It can easily implement customized actions
  3. It is generally a short coded language

Symbol Table

  • $ = JQuery symbol
  • $() = It accesses a html element
  • $(“selector”) = It accesses a specific element, such as div
  • S(“#selectorID”) = It accesses a specific element, such as #divID
  • $(“.class”) = It accesses an element by class name
  • $(“tag”) = It accesses an element by tag name:
    • $(“tag:nth-child(n)”)
  • .html = It shows content without html symbols
  • .alert = It shows content in the form of a pop-up box
  • .text = It shows content with html symbols

1. Open up your editor

The first step is to find a JQuery editor. There are several options:

  1. Download an editor
  2. Call the JQuery editor from your HTML <head>: <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”>
  3. Use an online free editor . This is the option I will be following in this tutorial.

2. Run the first line of code (.html)

JQuery HTML
JQuery HTML

Write the above code in your JQuery editor. This script will generate Hello World! in the HTML page. Let’s explain what each part of the above code means:

  1. https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js calls the JQuery library.
  2. $(document).ready(function(){} means to run the function when the HTML page is completely loaded.
  3. $(“#divID”).html(“Hello World!”); means to access a tag called divID, while html displays the content. Remember to add the hashtag symbol (#) in front of the tag name!
  4.  

    defines a tag called divID in which the code will be displayed. The code cannot being displayed unless the divID is added to the <body>.

3. Run JQuery code when the page is loaded (alert)

JQuery Alert
JQuery Alert

The code above is similar to the one described in point 2. The only difference is in the line alert(“Hello World!”);. If we add .html, we print the code, if we add .alert, we generate a pop-up box.

4. Show Content: the difference between .html and .text

JQuery HTML
JQuery Style Generation

VERSUS

JQuery Text
JQuery Text

The above example shows how a simple substitution, .text instead of .html changes the code result. In the first case, JQuery reads the code as HTML and therefore reads <h1></h1> as Headline H1 style. The result is Hello World in H1 (headline) style. In the second instance, JQuery reads the code as simple text and therefore ignores the HTML code and simply prints out the code as it is written.

CSS Style

In the next 4 points we will learn how to use JQuery to deliver CSS style using:

$(“selector”).css(“style”)

5. Show Content: Set CSS style using a Tag OR a Class Name

JQuery CSS Style
JQuery CSS Style

In the above example, the JQuery function has a name, changeColor() which aims to change the background from gray to red when the user click on it. The name is optional, you could call it Sheldon() and the result would not change (as long as you call the action onclick=”Sheldon”). As previously stated, the JQuery function that allows to generate CSS is: $(“selector”).css(“style”). In our example, we use a tag as $(“selector”). Because this tag is not a generic div, we need to add a hashtag (#) in front of it. Therefore, the $(“selector”) becomes $(“#divTest”). Again, we could call #divTest, anything we fancied, for instance #divLeonard. If we wanted to use a Class Name instead of a Tag Name, the $(“selector”) would become $(“.Class”) such as $(“.divTest”). 

Finally, we need to add a .css(“style”). In our case, we decided to change the background from an original color (displayed when the page loaded) into red. Therefore, it becomes .css(“background-color”, “red”).

In the body, we need to call a <div> where its id=”divTest”. If instead we decided to use a .Class Name, we would have called class=”divTest”.

Then, we need to call the JQuery function changeColor() that gets loaded not when the page loads but when people click. Therefore, we need to add the line onclick=”changeColor()”.

Finally, we add some style that defines the initial background, the background-color is grey (#cccccc) and it is 300px wide and 20px in height (Top-right). The cursor becomes a pointer (little hand) when the user mouse over the grey block (cursor: pointer;).

Now we are ready to rock: mousing over the grey box turn the mouse arrow into a pointer and if clicked, the background turns from grey (Top-right) into red (Bottom-right).

6. Show Content: Set CSS by tag

JQuery Set Font Style Italic
JQuery Set Font Style Italic

In this example, we want to change the font-style of  our <p> elements to Italic by clicking on a button. However, we do not want to change every single <p> element of our <body> but only the second one. As shown in the previous example (point 5) we need to define a JQuery function. In this case we name it setCSS(). Then we need to apply the JQuery code that modifies the CSS:  $(“selector”).css(“style”). In this example, our $(“selector”) is the <p> element. Therefore, the $(“selector”) becomes $(‘p’) (note the change from double to single apex). Then we added the line :nth-child(n) to indicate that the function would be limited to specific <p> elements. As we decided to change only the second <p> the final code becomes $(‘p:nth-child(2)’). As .css(“style”), we add .css(“font-style”, “italic”) code to changes the font-style to italic.

In the body we need to call at least two <p> elements, otherwise our code won’t work. We two Hello World! separated by two <p> elements. Finally, we add a button that if clicked calls the JQuery function (onclick=”setCSS()”). By clicking the button, the text defined by the second <p> element turns into Italic: from Hello World! into Hello World!.

7. Show Content: Set CSS by eq(n)

JQuery Style using eq(n)
JQuery Style using eq(n)

In this example I had a little bit of fun by changing a French Flag into an Italian one on the click of a mouse. To begin with the function is called changeColor(). As we did previous examples, we used a div tag as $(“selector”), which becomes $(“div”). No hashtag (#) as the tag is generic and is not identified by an id. The code eq(n) indicates that a specific number of “div” will be changed. In this case the first one (indicated by zero!). The .css(“Style”) code states that the background will change into a green color.

In the body, each div is identified by a specific style:

  1. Float: left; = The div element aligns on the left of the body
  2. Background-color = Blue, White and Blue
  3. width: 150px; height:120px = Size of the background

The function is again loaded on the click of a mouse (onclick=”changeColor()). After clicking the button ClickMe (value=”ClickMe”), the first div changes from background blue to green. Voila`, we changed a French Flag into an Italian one! So…why is that? Because we called a function (changeColor()) with a click of a mouse (onclick). The changeColor() function is applied only to the first (eq(0)) div $(“div”) and states a change of background-color, specifically into green.

8. Show Content: Set CSS by first or last

JQuery Set First
JQuery Set First

A result similar to the one described above (point 7) can be achieved by setting the $(“selector”) to either the first or the last div element. In the first case the $(“selector”) is defined as $(“div:first”), while in the second case is defined as $(“div:last”). After clicking on the ClickMe button the background of the first div turns from green to red as it calls the JQuery function changeColor(). If the $(“selector”) was defined as $(“div:last”), it would be the background of the last div to change color. In the above example, it would be blue box to turn red as it represents the background of the last div element.