What is jquery user interface. Installing the jQuery UI library

The jQuery UI (User Interface) library is a set of template elements for creating a user interface and is part of the jQuery library. User interface refers to the interaction between the user and the web page.

The main goal of the jQuery UI library is to make life easier for web developers so that they do not waste time on performing the same type of tasks. The most commonly found JavaScript scripts on websites have been collected into one library, and developers just need to take and apply the necessary parameters and methods. Developing user interfaces has become much faster.

Calendars, sliders, and pop-ups used on websites have already become a mandatory attribute. So why does a developer need to write code from scratch every time? When he can customize a ready-made template and use it on his website.

Connecting jQuery UI

Official website: https://jqueryui.com/

The jQuery UI library can be downloaded to your computer or connected via a CDN link.

Connection via CDN



You have two options for downloading the library.

Custom Download

You definitely don't need to download the entire library if you are only going to use some individual components. On the Download Builder page, you uncheck all the boxes except the components you need. For example, if you only need the accordion widget, then put a tick in the checkbox next to it and the site will tell you what elements will be needed for work. The checkboxes will be placed automatically where necessary and you will not download unnecessary files, which will have a positive effect on the site loading speed.

Before clicking the download button, choose a suitable theme for a beautiful design of the components. You can look at the visual design of ready-made themes in the Theme/Gallery section.

To embed components already into a stylized website, the theme designer is more suitable for you - ThemeRoller, go to the Theme section. When you change the appearance control panel, you will immediately see what all widgets look like. After you finish creating the appearance of the element, click on the download button and download only the selected elements and theme, which is very convenient.

Full download - Quick Download

The situation where you need the entire library is unlikely, unless you look at the source code. To download the full latest version, click on the button: Stable.

The downloaded library is connected in the same way as via CDN, with the only difference being that the URLs of the links will lead to the folder where you put these files on your hosting.



In the Demos section you can clearly see which tasks (demo examples) on the site can be solved using the library.

Let's look at the example of a widget - Tooltip. The purpose of this widget is to beautifully open the tooltip specified in the title attribute.

We create the HTML structure as usual. In paragraph p we place an input field for your age - input . In the text field we specify the title attribute with text "Please indicate your age". We will apply the tooltip widget to this element.



Your age:


After loading the DOM tree, on the document object we will call the tooltip method. We access the entire page (document) at once so that this method can be applied to other page elements. After calling the tooltip method, the title attribute values ​​will be displayed in a tooltip.

This is my formula to make a simple crawler in Node.js. This is the main reason for wanting to manipulate the DOM on the server side and is probably the reason you are here.

First use request to load the page to be parsed. Once the loading is complete, handle it with cheerio and start manipulating the DOM just like you would with jQuery.

Working example:

Var request = require("request"), cheerio = require("cheerio"); function parse(url) ( request(url, function (error, response, body) ( var $ = cheerio.load(body); $(".question-summary .question-hyperlink").each(function () ( console .info($(this).text()); )) ) parse("http://stackoverflow.com/");

This example will display in the console all the top questions displayed on the SO home page. This is why I love Node.js and its community. It couldn't be easier :-)

Install dependencies:

npm request to install cheerio

And run (if the script is above in the crawler.js file):

Encoding

Some pages will have non-English content in a certain encoding and you will need to decode it to UTF-8. For example, a page in Brazilian Portuguese (or any other language of Latin origin) will most likely be encoded in ISO-8859-1 (a.k.a. "latin1"). When decoding is required, I suggest that request not interpret the content in any way and instead use iconv-lite to do the job.

Working example:

Var request = require("request"), iconv = require("iconv-lite"), cheerio = require("cheerio"); var PAGE_ENCODING = "utf-8"; // change to match page encoding function parse(url) ( request(( url: url, encoding: null // do not interpret content yet ), function (error, response, body) ( var $ = cheerio.load(iconv. decode(body, PAGE_ENCODING)); $(".question-summary .question-hyperlink").each(function () ( console.info($(this).text()); )) ) parse( "http://stackoverflow.com/");

Before starting, install dependencies:

npm request to install iconv-lite cheerio

And finally:

Following links

The next step is to follow the links. Let's say you want to list all the posters from every top question on SO. You should first list all the top questions (example above) and then enter each link, parsing each page of questions to get a list of the users involved.

When you start following the links, the callback hell will start. To avoid this you should use some kind of promises, futures or something else. I always keep async in my toolbox. So here's a complete crawler example using async:

Var url = require("url"), request = require("request"), async = require("async"), cheerio = require("cheerio"); var baseUrl = "http://stackoverflow.com/"; // Gets a page and returns a callback with a $ object function getPage(url, parseFn) ( request(( url: url ), function (error, response, body) ( parseFn(cheerio.load(body)) )); ) getPage(baseUrl, function ($) ( var questions; // Get list of questions questions = $(".question-summary .question-hyperlink").map(function () ( return ( title: $(this). text(), url: url.resolve(baseUrl, $(this).attr("href")) )).get().slice(0, 5); // limit to the top 5 questions // For each question async.map(questions, function (question, questionDone) ( getPage(question.url, function ($$) ( // Get list of users question.users = $$(".post-signature .user-details a").map(function () ( return $$(this).text(); )).get(); questionDone(null, question); )); ), function (err, questionsWithPosters) ( // This function is called by async when all questions have been parsed questionsWithPosters.forEach(function (question) ( // Prints each question along with its user list console.info(question.title);

question.users.forEach(function (user) ( console.info("\t%s", user); ));


));

)); ));
Question: Incorrect jQuery connection in Wordpress

When connecting a plugin in a WordPress post, the plugin does not see jquery and the console naturally responds:
1 2 3 < script>JQuery(...).rotator is not a function


In the same entry, right before connecting the plugin, there is:

Javascript

if (window.jQuery ) ( alert("ss" ) ; )

Which returns ss. I connected it in functions.php, incorrectly in header.php, installed a plugin for connecting jquery on pages - damn it, it doesn’t work.
Thank you very much in advance to everyone who paid attention.
Answer:

Moderator's comment


Ruslaner___, hmm, cross-posting on the forum is prohibited
warning to you
1 2 3
warning to you
1 2 3 4 5 6 7 8 9 10 11 12 Question: Connecting JQuery UI

I'm trying to connect JQuery UI as follows. Between the head tags I add libraries and a css file:

HTML5 code

$("#slider").slider(( range: "min", min: 1, max: 100, value: 37, slide: function(event, ui) ( $("#amount").val("$ " + ui.value); ) ));

$("#amount").val("$" + $("#slider").slider("value"));
1 2 3 4 5 And between the body tags I’m trying to display the same slider

As a result, nothing is output. I checked with firebug, no errors were found. What should I do to make it work?


What a stupid thing jQuery doesn't work.
HTML5
1 2 3 4 5 6 7 8 9 10 11 12 Website< script type= "text/javascript" src= "js/jquery-ui-1.8.12.custom.min.js" >

That's all! You can then use the jQuery UI features on your page. For example, using one line of javascript code to make a regular element draggable:

~lt~!DOCTYPE html~gt~ ~lt~html~gt~ ~lt~head~gt~ ~lt~meta http-equiv="Content-Type" content="text/html; charset=UTF-8" / ~gt~ ~lt~script src="http://code.jquery.com/jquery-1.8.3.js"~gt~~lt~/script~gt~ ~lt~script src="/ui/jqueryui .custom.js"~gt~~lt~/script~gt~ ~lt~link type="text/css" href="/ui/jqueryui.custom.css" rel="stylesheet" /~gt~ ~lt ~style~gt~ body(font:9pt Arial,sans-serif;) p(color:#888; margin:8px 0 12px 0) #draggable(width:125px; height:125px; padding:0.5em; border:1px solid #ddd; background-color:#eee) ~lt~/style~gt~ ~lt~/head~gt~ ~lt~body~gt~ ~lt~div id="draggable"~gt~ ~lt~p ~gt~Dragable element~lt~/p~gt~ ~lt~/div~gt~ ~lt~script~gt~ $("#draggable").draggable(); // this line of code that makes the element draggable ~lt~/script~gt~ ~lt~/body~gt~ ~lt~/html~gt~

Working with plugins

All behavior and widget plugins operate in a similar way. Each jQuery UI plugin is represented by one main method that is called on the selected elements. Its name always matches the name of the plugin. Using this method, you can instantiate (install) a plugin on elements, find out and change plugin properties, install event handlers, and also run plugin functions, which are usually called methods (although they are not methods in the usual sense of this concept).

Instantiation (installation)

To install any plugin on page elements, just select the necessary elements using jQuery and then call the plugin method on them (the name of which always matches the name of the plugin):

Methods

Typically, a method of an object in javascript means a function called on this object as follows:

obj.A();

// call method A on object obj obj.B () ;

// call method B on object obj

However, within the framework of working with specific jQuery UI plugins, methods are called this form of recording:

$("#someId" ) .plaginName ( "method name" , method parameters) ;

For example:

// make a dialog box from the element with id=someId using // the dialog plugin and specify a title for the window $("#someId" ) .dialog (( title: "Message" ) ) ;

// make the first div on the page a calendar using // the datepicker plugin, and specify the minimum and maximum date $("div:first") .datepicker (( minDate: new Date(2007, 1 - 1, 1) , maxDate: new Date(2013, 1 - 1, 1) ) ;

In addition, the value of any property can be found out or changed after the plugin has been instantiated. To do this you need to use the "option" method:

// find out the title of the dialog box var dialogTitle = $("#someId" ) .dialog ("option" , "title" ) ;

// change the title by adding the prefix "#1 " $("#someId" ) .dialog ("option" , "title" , "#1 " + dialogTitle) // change the minimum date in the calendar // which is installed to the first div on the page $("div:first" ) .datepicker ("option" , "minDate" , new Date(2008 $("selector" ) .dialog (( close : function (event, ui) ( ... ) ) ) ;

Creating your own plugins

In addition to organizing many convenient and intuitive plugins, jQuery UI provides a means by which you can make similar plugins yourself - the UI Widget Factory. One of its big advantages is that it organizes some OOP capabilities that allow you to modify existing widgets and create your own widget hierarchies.

jQuery UI is a set of widgets and plugins from the jQuery developers themselves. In my opinion, this tool needs to be studied as much as necessary so as not to write your own “bicycles”. You can download and read about this add-on for jQuery on the project home page - http://jqueryui.com/.

What do we need to know about widgets and plugins? The first is what they are, and the second is how they work. I will try to dwell on these two points.

  • Interactivity
  • I'll start with useful plugins that can make life easier when creating interactive interfaces:
  • Draggable – this component allows you to make any DOM element draggable with the mouse
  • Droppable is a logical extension of the Draggable component; necessary for working with containers into which you can drag and drop elements
  • Resizable – as the name suggests, allows you to resize any DOM elements
Widgets

Widgets are already a comprehensive solution containing not only JavaScript code, but also some implementation of HTML and CSS:

All widgets and plugins are tied to the jQuery UI core, but there are also dependencies between the plugins themselves and it’s worth keeping them in mind. But don't worry - when building a jQuery UI package, all dependencies are checked automatically, i.e. when you need a previously unconnected widget, it is better to download the assembly again.

Utilities

We don’t have many utilities - here is a useful Position plugin that allows you to control the position of DOM elements - http://jqueryui.com/position/, and there is also a factory for creating widgets, but I’ll tell you about it a little later.

Effects

Among the effects jQuery UI provides, I highlight four points:

  • Color Animation
  • Class change animation
  • Effects set
  • Expanding easing capabilities

The “Effects Core” component is responsible for color animation, which allows you to animate color changes using the “.animate()” function:

$("#my" ).animate(( backgroundColor: "black" ), 1000 );

Yes, yes, basic jQuery cannot do this, but jQuery UI allows you to animate the following parameters:

  • backgroundColor
  • borderBottomColor
  • borderLeftColor
  • borderRightColor
  • borderTopColor
  • color
  • outlineColor

Another feature contained in “Effects Core” is the animation of changes in the class of a DOM element, i.e. when you assign a new class to an element, instead of the usual instant application of new CSS properties, you will see an animation of these properties from the current ones to those specified in the assigned class. To use this functionality, we will need old friends - the “.addClass()”, “.toggleClass()” and “.removeClass()” methods, with only one difference - when calling the method, the animation speed must be specified as the second parameter:

$("#my" ).addClass("active" , 1000 ); $("#my" ).toggleClass("active" , 1000 ); $("#my" ).removeClass("active" , 1000 );

If from the previous paragraph you do not have an understanding of what is happening, then this code is for you:

#my ( font-size :14px ; ) #my .active ( font-size :20px ; ) $(function () ( $("#my" ).addClass("active" , 1000 ); // here it turns out the same way next call $("#my" ).animate(("font-size" :"20px" ), 1000 ));

There is also a “.switchClass()” method that replaces one class with another, but I have never found it useful.

I won’t talk long about the set of effects; it’s better to see them in action on the page http://jqueryui.com/effect/. To work with effects, the “.effect()” method appears, but it is better not to use it by itself, because the UI has expanded the functionality of the built-in methods “.show()”, “.hide()” and “.toggle()”. Now, by passing the name of the effect as the animation speed parameter, you will get the desired result:

$("#my" ).hide("puff" ); $("#my" ).show("transfer" ); $("#my" ).toggle("explode" );

I’ll give a list of effects, maybe someone will remember: blind, bounce, clip, drop, explode, fold, highlight, puff, pulsate, scale, shake, size, slide, transfer.

If at any point in time you need to make changes to the theme, open the file “jquery-ui-#.#.##-custom.css” and find the line starting with the text “To view and modify this theme, visit http:.. ." Follow the link provided and use ThemeRoller to make the necessary changes.

We write our own widget

The starting point for you when writing a widget for jQuery UI will be the official documentation, but since not everyone has good knowledge of English, I will try to translate and adapt the information presented in it.

The first thing worth talking about is that the rules for writing plugins for jQuery are too imposing, which does not contribute to their quality. When creating jQuery UI, we decided to go by standardizing the process of writing plugins and widgets. I can’t say how successful the idea was, but it was clearly better than it was. I'll start by describing the framework for your widget:

$.widget("book.expose" , ( // default settings options: ( color: "red" ), // widget initialization // make changes to the DOM and attach handlers _create: function () ( this .element; / / searched object in jQuery wrapper this .name; // name - expose this .namespace; // space - book this .element.on("click." +this .eventNamespace, function () ( console .log("click " ); )); ), // the method is responsible for applying the settings _setOption: function ( key, value ) ( // apply changes to the settings this ._super("_setOption" , key, value); ), // the _destroy method should be the opposite of _create // it should remove all changes made to the DOM and remove all handlers, if any, _destroy: function () ( this .element.off("." +this .eventNamespace); ) ));

Let me explain for those who haven't read the comments:

options – storage of widget settings for a specific element

Create() – is responsible for initializing the widget – here changes should occur in the DOM and event handlers should be “hung”

Destroy() is the antipode to “_create()” - it should clean up everything that we have littered

SetOption(key, value) – this method will be called when trying to change any settings:

$("#my" ).expose((key:value))

An observant eye will notice that all of the listed methods begin with an underscore - this is a way to highlight “private” methods that are not available for execution. If we try to run "$("#my").expose("_destroy")", we will get an error. But keep in mind - this is just an agreement, keep it!

To bypass the privacy agreement, you can use the “data()” method:

$("#my" ).data("expose" )._destroy() // place for the smiley "(evil)"

In this example, I tried to set a good tone for writing widgets - I “hung” event handlers in the namespace. This will give you the opportunity to control what is happening in the future without having to go into the widget code. "True story".

The code described in the “_destroy()” method is redundant, because it is already executed in the public “destroy()”. Presented here for clarity.

And for the lazy, in order not to write “eventNamespace” in event handlers every time, the developers added two methods in version 1.9.0: “_on()” and “_off()”. The first one takes two parameters:

  • DOM element or selector or jQuery object
  • a set of event handlers as an object

All listed events will “hang” in the “eventNamespace” space, i.e. the result will presumably be the same:

this ._on(this .element, ( mouseover:function (event ) ( console .log("Hello mouse" ); ), mouseout:function (event ) ( console .log("Bye mouse" ); ) ));

The second method, "_off()", allows you to selectively disable handlers:

this ._off(this .element, "mouseout click" );

Well, the frame is a longboat, it’s time to move on to functionality. Let's add an arbitrary function with arbitrary functionality:

CallMe:function () ( console .log("Hello?" ); )

We can easily access this function both from other widget methods and from outside:

// from inside this .callMe() // from outside $("#my" ).expose("callMe" )

If your function takes parameters, then they are passed in the following way:

$("#my" ).expose("callMe" , "Hello!" )

If you want to reach a widget method in the event handler, then do not forget about the variable scope and do the following maneuver:

( _create: function () ( var self = this ; // here it is! this .element.on("click." +this .eventNamespace, function () ( // use self here, because this already points to // element on which we click self.callMe(); )) ) )

Okay, let's go, now let's talk about the events. For more flexible development and implementation of widgets, functionality is provided for creating arbitrary events and “listening” to them:

// trigger the event this ._trigger("incomingCall" ); // subscribe to the event when the widget is initialized $("#my" ).expose(( incommingCall: function (ev ) ( console .log("din-don" ); ) )) // or after, using the event name // widget name + event name $("#my" ).on("exposeincomingCall" , function () ( console .log("tru-lya-lya" ) ));

There is a lot of material, I understand, but I will also add a description of several methods that can be called from the widget itself:

Delay() – this function works like “setTimeout()”, only the context of the passed function will point to the widget itself (this is so as not to bother with the scope)

Hoverable() and _focusable() – these methods need to be fed elements for which it is necessary to listen for the “hover” and “focus” events in order to automatically add the “ui-state-hover” and “ui-state-focus” classes to them when they occur these

Hide() and _show() – these two methods appeared in version 1.9.0, they were created to standardize the behavior of widgets when using animation methods; Settings are usually hidden in options under the “hide” and “show” keys, respectively. The methods should be used as follows:

( options: ( hide: ( effect: "slideDown" , // settings are equivalent to calling duration: 500 // .slideDown(500) ) ) ) // calls to _hide() and _show() should be used inside the widget this ._hide(this .element, this .options.hide, function () ( // this is our callback function console .log("hidden" ); ));

There are a couple more methods that were implemented before us:

( enable: function () ( return this ._setOption("disabled" , false ); ), disable: function () ( return this ._setOption("disabled" , true ); ) )

In fact, these functions create a synonym to call:

$("#my" ).expose(( "disabled" : true )) // or false

Our task is simply to track this flag in the “_setOption()” method.