jQuery Fundamentals for APEX PL/SQL programmers

jQuery Fundamentals for APEX PL/SQL programmers

Mastering the concept of selectors is a difficult part of learning jQuery. There are a number of methods to identify the right page element to act upon. In addition to the selectors mentioned in this blog, jQuery also provides the ability to traverse up and down the HTML tree using specific functions.

More detailed examples of selectors will be introduced as the blog details traversal methods in addition to other fundamental concepts and common features. Just like SQL, a good percentage of what you’ll ever need to do will already have an appropriate documented function.


Table of contents[Show]


To get a deeper understanding of jQuery, I would recommend a book dedicated to the topic. Pro jQuery, by Adam Freeman (Apress), provides a comprehensive introduction to the jQuery language.

 

Including jQuery in Your APEX Page

Listing 1 shows how a recent version of the jQuery library from a Content Delivery Network (CDN) can be included on any page, in addition to a style definition used in the following examples.

Listing 1 Extend Sample Page to Include jQuery and Styling

<script type="text/javascript"
               src="https://code.jquery.com/jquery-1.11.1.js"></script>
 
 <style> 
 .coolCat {
   font-weight:bold;
 } 
 </style>

The supplied sample page places it between the closing body and HTML tags. The exact placement of this code isn’t that important for a sample page like this one; HTML is interpreted with great tolerance by many of the browsers. Normally, style content is placed in the HEAD tag, or preferably included as a .css style sheet file separate from the HTML document.

The best placement for script content changes over time, but the current rule of thumb is to place or include files near the closing BODY tag.

The examples in this blog can be applied to the sample page via browser console, as shown in Figure 1. The text with greater-than symbol (>) prefixes is what I typed into the console. From APEX 4.0, pages have core jQuery libraries built in.

 Your first jQuery commands run in the browser console

Figure 1. Your first jQuery commands run in the browser console

 

Getting and Setting

The “Hello Universe” example in the SQL analogy used in this article introduced a jQuery function that sets a value. Typically, the types of functions that access attributes of page elements are overloaded such that they will either show the current value of the specified attribute of those elements or set it if a parameter is passed.

Often the difference between getting and setting a value is the presence of a parameter. The first command in the following example gets a value. The second command sets the attribute to the actual parameter value that is passed.

Enter the following commands in the Console tab and consider the output:

$(’h1’).text();
$(’h1’).text(’Hello Universe’);

In this case, the attribute is the text within the h1 element. Classes and height/width dimensions can also be manipulated with jQuery.

The sample page will also includes a simple CSS class called coolCat that will apply boldness to any text with that class. For example:

<li class="coolCat"> Neil deGrasse Tyson

jQuery provides the ability to apply the same attribute in response to whatever event you require. To apply this class to all list item elements, use the .addClass() function. The selector is the LI tag, indicating all such tags within the page. The function’s parameter indicates the class name to add to the selected element:

$(’li’).addClass(’coolCat’);

The following are get/set functions you might find used within an APEX environment.

  • attr()
  • prop()
  • data()
  • is()
  • css()
  • removeClass()
  • toggleClass()
  • height()
  • width()

 

Traversing

jQuery provides a number of functions that allow you to traverse the DOM. This means that when starting at one selector, you can move up the tree representing the web page, and down the tree, or even sideways across list elements or table rows and cells.

Before you start traversing the DOM, it is good practice to specify the appropriate set of elements or starting point. For instance, there may be more than one unordered list on a page, so specify the list with the ID of the list in the selector:

$(’#communicators li’)

Using jQuery for Oracle APEX PL/SQL coding 

Siblings

The items inside the #communicators list are considered siblings to each other. To specify certain nodes within a set of siblings such as list elements, a number of pseudo-selectors is available. These pseudo-selectors can be applied within the selector or using jQuery functions defined for traversing.

To return the first list item in a set, you would use the selector :first. However, you could also use the jQuery function first(). This means the following statements return Carl Sagan, though performance may vary:

$(’#communicators li:first’).text()
$(’#communicators li’).first().text()

To honor Neil deGrasse Tyson’s former dancing skills and make him the the coolCat while leaving everyone else normal, jQuery can identify a specific element in the list. The items in the list can be treated like an array with the function eq(), where the parameter is the position within the array:

$(’#communicators li:eq(1)’).addClass(’coolCat’);

Like JavaScript, arrays start counting from zero. Tyson is the second name in the list, and thus we refer to him via the index value 1.

Using the coolCat class as the selector that identifies Tyson, return the set of list item siblings with the following snippet:

$(’.coolCat’).siblings()
[<li>Carl Sagan</li>, <li>Eugenie Scott</li>]

 

Ancestry

The terminology used in traversing up and down the tree is the same as you’d use for your family. In our sample page, we can start from UL using #communicators, or from the second list item with the class attributed to Neil Tyson using li.coolCat.

List items are descendants of #communicators, accessible using functions like children() and find(). For example, you can retrieve the text of the list items in #communicators as follows:

$(’#communicators’).children()
[<li>Carl Sagan</li>,<li class="coolCat">Neil Tyson</li>,<li>Eugenie Scott</li>]

The next example finds any elements underneath #communicators with the class .coolCat. This might be the next level under as in the sample page, or it could be any number of nodes deep.

$(’#communicators’).find(’.coolCat’)
[<li class="coolCat">Neil Tyson</li>]

When moving up the tree using functions closest() and parent(), the latter takes one step up the tree at a time while the former will look for selectors anywhere in the ancestry, similar to find().

I prefer closest() as it’s less likely to break when the page is modified. If the target node is a few levels higher, it saves chaining a number of parent() together. More on chaining in the next section.

Here jQuery starts at any list elements with the class .coolCat, and then traverses up to the closest unordered list. In this case, parent() would accomplish the same task.

$(’.coolCat’).closest(’ul’)
[<ul id="communicators">...</ul>]

Then you can move up another level with .parent():

$(’.coolCat’).closest(’ul’).parent()
[<body>...</body>]

BODY and HTML are considered ancestors to everything underneath them. In our example page, the unnumbered list is immediately inside the HTML body. That’s why the BODY tag is returned as the parent of the list.

These examples show jQuery and selectors can be interchanged in a number of different ways to identify elements of the page. Finding the right balance can be difficult, particularly when learning. Some will perform better, while others will seem more elegant. I’ll do my best to show the methods I’ve found that work best for me in the given situation.

 Note

 

Chaining

Chaining is a natural part of jQuery that is utilized frequently to run multiple jQuery methods on the same element with a single statement. This could be likened to updating multiple columns in a SQL update statement.

To add the class to Tyson and shorten his name, use a jQuery function to identify the node.

Instead of executing two separate statements - one to add a class and another to set the text—we can chain the commands for efficiency and readability. Chaining simply means adding multiple function notation calls to the selector. For example, to add the class to Tyson and shorten his name, you would use the following:

$(’#communicators li’).eq(1).addClass(’coolCat’).text(’Neil Tyson’);

For readability—particularly with longer chains—you can format the statement over multiple lines, just like in SQL:

$(’#communicators li’)

   .eq(1)
   .addClass(’coolCat’)
   .text(’Neil Tyson’);

The selector supplied to jQuery locates all list items within #communicators, and then filters the list to just the second element. The class is then added and the element text modified.

The browser takes longer to complete the actions if written as multiple statements. jQuery needs to locate the selector each time, and it won’t have the advantage of Oracle’s optimization techniques for frequently accessed information. Therefore, the following two statements will take longer to complete than the previous chained example:

$(’#communicators li:eq(1)’).addClass(’coolCat’)
$(’#communicators li:eq(1)’).text(’Neil Tyson’);

 

Effects

The term effect in jQuery refers to what you want to have happen to the elements you’ve selected. Simple, yet effective effects can be applied to whatever selector is used.

Some jQuery examples with obvious outcomes include the functions .hide() and .show(). These effects set the display property of the selected elements to none, as in display: none.

You may have already utilized these effects with the corresponding APEX JavaScript APIs $x_Show() and $x_Hide(). Other APIs also exist to traverse the tree. One example similar to .closest(), is $x_UpTill().

Other methods provide animated effects, such as .slideDown() and .fadeOut().

Visit the API documentation to determine the parameters available to these functions that I’ve mentioned. For example, find the parameters to .slideDown() at the following URL.

The URL pattern is consistent. Replace slidedown in the URL with hide or show or the name of any other function of interest.

Alternatively, you get help by quickly googling the function name, as in “jquery slidedown.”

Figure 2 shows the start of what is a concise documentation format; it’s the documentation for .slideDown. Further down the page are details regarding available options along with a simple description of what the function does with a basic example of the function in action.

jQuery documentation for slideDown() 

 Figure 2. jQuery documentation for slideDown()

Sometimes related functions can be mentioned and linked to, particularly if deprecation has occurred with a newer release of jQuery.

 

Callbacks

Note the description for the complete parameter in Figure 2. It’s a function that’s called once the animation task has completed. These types of functions are called callbacks. They are used frequently within the jQuery framework to ensure processes are executed only upon successful completion of the task.

Statements are processed in JavaScript without regard to whether the prior statement has been executed. In this case, process B will start before process A may have finished:

processA;

processB;

Callbacks can ensure process B is only executed once process A finishes, typically by passing the second function as a parameter to the first.

 

AJAX Callbacks

There is another type of callback, known as an AJAX callback, that allows us to call PL/SQL. AJAX callbacks allow us to communicate between the JavaScript and database world.

I’ll go into further detail about the syntax variations available to bridge the gap between the browser and the database, but for now I want to mention the two main methods of invoking PL/SQL from the web page: dynamic actions and jQuery wrappers.

 

Dynamic Actions

You’ve actually defined an AJAX callback if you’ve ever defined a dynamic action that fires some PL/SQL as the result of some interaction on the page. APEX provides a declarative format to execute these calls, but JavaScript can provide added flexibility in more complex scenarios, in part since APEX doesn’t facilitate conditional actions.

Figure 3 shows an APEX dynamic action invoking PL/SQL. APEX 5.0 also kindly indicates my sample function does not exist in the database. The Page Items to Submit attribute indicates which items need values sent from the web page to session state in the database. Comma separated items in Page Items to Return will list which page items should be updated to reflect value from session state.

Dynamic action calling PL/SQL

Figure 3. Dynamic action calling PL/SQL

 

APEX jQuery Wrapper

The same PL/SQL in the dynamic action can be invoked using JavaScript. In fact, APEX converts dynamic actions to just that. The next example is representative of what APEX generates to serve the dynamic action. Instead, this case invokes PL/SQL in an AJAX callback called “MY_CALLBACK.” It will also set the PL/SQL package variable apex_application.g_x01 to whatever value is found in the browser for item P1_EMPNO. From APEX 5 this information is also accessible using substitution strings APP_AJAX_01 through APP_AJAX_10.

apex.server.process("MY_CALLBACK"
   , {x01 : $v(’P1_EMPNO’)}
 ).done(function(pData) {

  /* pData returned from database using htp package or proxy */
 
});

Embedding this as JavaScript provides advantages such as the ability to execute only under specific conditions in a workflow. It will call certain code upon success or failure. Attributes APEX provides declaratively are available as optional parameters.

 

Summary

jQuery is not that complicated. All you need to do is identify the part of the web page to update with a selector and then apply a function to that page element.

You can chain functions together, applying all to the selected elements. You can also traverse the tree in any direction from a given selector, perhaps locating a key node from a click event further down the tree.

Most importantly, you can execute PL/SQL on demand from within JavaScript and pass information back and forth. This allows an integration between the browser and database that enriches the user interfaces by minimizing the amount of entire page submissions required.

 

 

Вас заинтересует / Intresting for you:

jQuery Events for APEX & PL/SQ...
jQuery Events for APEX & PL/SQ... 2788 views Гвен Sun, 03 Jun 2018, 11:28:11
Understanding the CSS Selector
Understanding the CSS Selector 4490 views Игорь Воронов Wed, 18 Sep 2019, 12:39:02
Oracle Application Express (AP...
Oracle Application Express (AP... 2822 views Doctor Fri, 20 Jul 2018, 17:56:09
What is CSS Selectors?
What is CSS Selectors? 2371 views Гвен Sun, 03 Jun 2018, 10:28:57
Comments (0)
There are no comments posted here yet
Leave your comments
Posting as Guest
×
Suggested Locations