How to use jquery

How to use jquery

jQuery для начинающих

How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

jQuery — это замечательный JavaScript Framework, который подкупает своей простотой в понимании и удобством в использовании. Но изучение надо с чего-то начинать, и лично моё мнение — лучше всего начинать с наглядных примеров, и они далее…

Как же все-таки работает jQuery?

Ну для начала Вам понадобиться сам фреймворк, его вы сможете скачать с домашней страницы проекта, затем проинициализировать:

А основные моменты Вам поможет понять следующая диаграмма:
How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

Как получить элемент с помощью jQuery?

Выдвижная панель

Начнем с простенького примера — слайд-панель, она у нас будет двигаться вверх/вниз по клику на ссылке (см. пример)
How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery
Реализуем это следующим образом, по клику на ссылку, у нас будет переключаться её класс (между «active» и «btn-slide»), а панелька с будет выдвигаться/прятаться. (класс «active» изменяет позицию фонового изображения, см. CSS файл во вложении).

Магические исчезновения

Этот пример покажет как можно красиво и легко убирать растворять элементы (см. пример):
How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

, и его прозрачность будет медленно изменяться от opacity= 1.0 до opacity=hide:

Связанная анимация

— уменьшаем его прозрачность до 0.1, наращиваем позицию left еще на 400px, со скоростью 1200 (milliseconds)
Line 3: затем медленно изменяем следующие параметры: opacity=0.4, top=160px, height=20, width=20; скорость анимации указывается вторым параметром: «slow», «normal», «fast» или в миллисекундах
Line 4: затем opacity=1, left=0, height=100, width=100, скорость — «slow»
Line 5: затем opacity=1, left=0, height=100, width=100, скорость — «slow»
Line 6: затем top=0, скорость — «fast»
Line 7: затем slideUp (с дефолтной скоростью анимации — «normal»)
Line 8: затем slideDown, скорость — «slow»
Line 9: возвращаем false для того чтобы браузер не перешел по ссылке

Гармошка #1

внутри

, для следующего в нём элемента

будет применен эффект slideToggle, затем для всех остальных элементов

будет применен эффект slideUp. Следующие действие изменяет класс заголовка на «active», затем ищем все остальные заголовки

и убираем у них класс «active»

Гармошка #2

Этот пример схож с предыдущим, лишь отличается тем, что мы указываем открытую по умолчанию панельку. (см. пример)

В CSS у нас указано для всех элементов

Анимация для события hover #1

Данный пример поможет создать Вам очень красивую анимацию для события hover (надеюсь, Вы знаете что это?), (см. пример):
How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

Когда Вы наводите мышкой на элемент меню (mouseover), происходит поиск следующего элемента , и анимируется его прозрачность и расположение:

Анимация для события hover #2

Кликабельные блоки

Складывающиеся панельки

— вызывает метод slideToggle для следующего элемента

Имитация Backend’a WordPress’a

(цвет изменяется на красный), и изменяет параметр «opacity» на «hide»

Галерея изображений

По клику на изображения в

Стилизируем ссылки

Так же Вы можете посмотреть все примеры или скачать jQuery tutorial for beginners.

Так же много полезных ссылок по jQuery найдете на следующей странице: http://blog.termit.name/jquery/

Может кому пригодиться еще библиотека jQuery-PHP

Getting Started with jQuery UI

link What is jQuery UI?

jQuery UI is a widget and interaction library built on top of the jQuery JavaScript Library that you can use to build highly interactive web applications. This guide is designed to get you up to speed on how jQuery UI works. Follow along below to get started.

link Start by Checking Out the Demos

To get a feel for what jQuery UI is capable of, check out the UI Demos.

In the demos section, the navigation lists all of the interactions and widgets that jQuery UI offers. Choose an interaction or widget and you’ll be presented with several demo configurations for that particular plugin. Each demo allows you to view source code, change themes, and the URL can always be bookmarked. For example, check out the accordion widget’s fill space demo page.

link Build Your Custom jQuery UI Download

Once you have a basic understanding of what jQuery UI is and what it does, you’re ready to try it out! It’s time to head over to the Download Builder on the jQuery UI website to download a copy of jQuery UI. jQuery UI’s Download Builder allows you to choose the components you would like to download and get a custom version of the library for your project. There are three easy steps to building your custom jQuery UI download:

link Step 1: Choose Which Components You Need

The main column of the Download Builder lists all of the JavaScript components in jQuery UI categorized into groups: core, interactions, widgets, and effects. Some components in jQuery UI depend on other components. Just check the boxes for the widgets you’d like to download and any required dependencies will automatically be checked as well. The components you select will all be combined into a custom jQuery UI JavaScript file.

How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

link Step 2: Select a Theme (or Roll Your Own Custom Theme)

In the right column of the Download Builder, you’ll find a field where you can choose from a number of pre-designed themes for your jQuery UI widgets. You can either choose from the various themes we provide, or you can design your own custom theme using ThemeRoller (more on that later).

Advanced Theme Settings: The theme section of the Download Builder also offers some advanced configuration settings for your theme. If you plan to use multiple themes on a single page, these fields will come in handy. If you plan to only use one theme on a page, you can skip these settings entirely.

link Step 3: Choose a Version of jQuery UI

The last step in the Download Builder is to select a version number. Make sure to check not only what version of jQuery UI you pick, but also the version of jQuery Core that version supports, as different versions of the library support different versions of jQuery. For more information on what’s new in each version of jQuery UI, see the project’s upgrade guides and changelogs.

link Click Download!

You’re finished with the Download Builder! Click the download button and you’ll get a customized zip file containing everything you selected.

link Basic Overview: Using jQuery UI on a Web Page

Next, open up index.html from the downloaded zip in a text editor. You’ll see that it references your theme, jQuery, and jQuery UI. Generally, you’ll need to include these three files on any page to use the jQuery UI widgets and interactions:

HTML:

JavaScript:

How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

link That’s It!

For demos of all of the jQuery UI widgets and interactions, check out the demos section of the jQuery UI website.

link Customizing jQuery UI to Your Needs

jQuery UI allows you to customize it in several ways. You’ve already seen how the Download Builder allows you to customize your copy of jQuery UI to include only the portions you want, but there are additional ways to customize that code to your implementation.

link jQuery UI Basics: Using Options

Each plugin in jQuery UI has a default configuration which is catered to the most basic and common use case. But if you want a plugin to behave different from its default configuration, you can override each of its default settings using «options». Options are a set of properties passed into a jQuery UI widget as an argument. For example, the slider widget has an option for orientation, which allows you to specify whether the slider should be horizontal or vertical. To set this option for a slider on your page, you just pass it in as an argument, like this:

You can pass as many different options as you’d like by following each one with a comma (except the last one):

Just remember to surround your options with curly brackets < >, and you’re well on your way. Of course, the example above barely touches on what you can do with jQuery UI. To get detailed information on the entire set of jQuery UI widgets, visit the jQuery UI documentation.

link Visual Customization: Designing a jQuery UI Theme

If you want to design your own theme, jQuery UI has a very slick application for just that purpose. It’s called ThemeRoller, and you can always get to it by either clicking the «Themes» link in the jQuery UI navigation, or simply going to jQuery UI ThemeRoller.

ThemeRoller provides a custom interface for designing all of the elements used by jQuery UI widgets. As you tweak the «levers» in the left column, the widgets on the right will reflect your design. The Gallery tab of ThemeRoller offers a number of pre-designed themes (the same ones offered by the Download Builder) that you can tweak or download as they are.

How to use jquery. Смотреть фото How to use jquery. Смотреть картинку How to use jquery. Картинка про How to use jquery. Фото How to use jquery

link Downloading Your Theme

When you click the «Download theme» button in ThemeRoller, you’ll be directed to the Download Builder and your custom theme will be auto-selected in the Theme dropdown menu. You can configure your download package further from there. Once you download, you’ll see that the example.html page is styled using your custom theme.

link Support: Where Can I Get Help?

JQuery UI user and developer resources are kept up-to-date at the Support Center.

link Developers Wanted!

Want to join the jQuery UI team? We’d love your help! Visit the UI Development Center for details on how to get involved.

How to use jQuery

The jQuery syntax is very straightforward and allows you to add advanced functionality to your website with a minimum of code. Here’s how to use jQuery on your site.

Here’s an example of some jQuery code:

Probably one of the most noticable things is that each line of code starts with dollar signs. These dollar signs are part of the jQuery syntax.

So the following two examples are equivalent:

No-Conflict Mode

Note that the dollar sign is not unique to jQuery. There are also other JavaScript libraries that also use a dollar sign. The dollar sign is simply a JavaScript identifier.

This could potentially lead to conflicts if you use another JavaScript library alongside jQuery. To avoid any conflicts, you can relinquish control of the dollar sign. This is referred to as «no-conflict mode».

You can put jQuery into no-conflict mode by inserting a line of code immediately after jQuery is loaded onto the page (and before you attempt to use jQuery in your page).

Just to be clear, under most circumstances, you won’t need to do this. You only need to do this if you want to relinquish the dollar sign as an alias to jQuery.

The ready() Method

Most jQuery code you encounter will probably be wrapped in one of the following (or some variation):

This is jQuery’s ready() method. This method allows you to run code as soon as the page’s Document Object Model (DOM) becomes safe to manipulate.

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.

You should still place your code inside the ready() method even if you wrap your code within an event handler (such as click() ). DOM objects still need to be loaded before attempting to apply event handlers against them.

The JavaScript Version

First, here they all are together:

The window.onload and load events will wait until everything has downloaded — even the stylesheets, images, banner ads, subframes etc.

The DOMContentLoaded only waits for the HTML document to be completely loaded and parsed, without waiting for stylesheets, images, banner ads, subframes etc to finish loading. Therefore, your code will typically run sooner than the window.onload and load events. This is usually a good thing, as images and banner ads tend to take longer to load than it takes to have the DOM ready.

jQuery’s ready() method only waits for the DOM to be ready also. However, there is an important difference that makes the jQuery option slightly more robust. According to the jQuery documentation:

Selectors

The basic concept of jQuery is, you select an element, then perform an action against that element.

Here are some examples:

jQuery uses selectors to select an element before applying an action to it.

In jQuery, the selector goes inside brackets and quotes. Like this:

You can also use more advanced selectors, such as these:

jQuery supports most CSS3 selectors and also some non-standard selectors.

Events

jQuery uses events to determine when a block of code should run.

Events are triggered when something happens within the DOM. Some events are triggered by user actions (such as the user clicks on an element, moves the mouse, etc), other events are triggered by the browser (such as the page has loaded, an animation has finished running, etc).

When you write jQuery/JavaScript, you need to specify when the code should run. If you don’t do this, then it will simply run when the browser loads it. Running a script as soon as the window loads isn’t always desirable. Most of the time you will only want the code to run once a certain event has occurred.

Here’s an example of attaching an event handler to a selection:

In this case, the code will run when the user clicks a button element.

The selector comes first (in this case button ), then the event handler (in this case click() ). A function is provided to the event handler, which is where you write your code (i.e. between the <> (curly braces)).

So we could combine that code with one of the previous examples, and we’d end up with this:

Here it is in action:

White Space

You can include white space within the brackets or leave it out. It doesn’t matter. For example, all of the examples are equivalent:

jQuery()

Contents:

jQuery( selector [, context ] ) Returns: jQuery

Description: Accepts a string containing a CSS selector which is then used to match a set of elements.

version added: 1.0 jQuery( selector [, context ] )

version added: 1.0 jQuery( element )

version added: 1.0 jQuery( elementArray )

version added: 1.0 jQuery( object )

version added: 1.0 jQuery( selection )

version added: 1.4 jQuery()

Selector Context

Using DOM elements

The second and third formulations of this function create a jQuery object using one or more DOM elements that were already selected in some other way. A jQuery object is created from the array elements in the order they appeared in the array; unlike most other multi-element jQuery operations, the elements are not sorted in DOM order. Elements will be copied from the array as-is and won’t be unwrapped if they’re already jQuery collections.

Please note that although you can pass text nodes and comment nodes into a jQuery collection this way, most operations don’t support them. The few that do will have an explicit note on their API documentation page.

A common use of single-DOM-element construction is to call jQuery methods on an element that has been passed to a callback function through the keyword this :

Cloning jQuery Objects

Returning an Empty Set

Working With Plain Objects

Examples:

Find all p elements that are children of a div element and apply a border to them.

Find all inputs of type radio within the first form in the document.

Find all div elements within an XML document from an Ajax response.

Set the background color of the page to black.

Hide all the input elements within a form.

jQuery( html [, ownerDocument ] ) Returns: jQuery

Description: Creates DOM elements on the fly from the provided string of raw HTML.

version added: 1.0 jQuery( html [, ownerDocument ] )

version added: 1.4 jQuery( html, attributes )

Creating New Elements

Filtering isn’t, however, limited to these tags. For example, Internet Explorer prior to version 8 will also convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

Tags that cannot contain elements may be quick-closed or not:

This behavior is expected. As of jQuery 1.9.0 (and unless using the jQuery Migrate plugin), jQuery() requires the HTML string to start with a (i.e text nodes cannot appear at the front of the HTML string).

Important: If the second argument is passed, the HTML string in the first argument must represent a simple element with no attributes. As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

How to use jQuery

The jQuery syntax is very straightforward and allows you to add advanced functionality to your website with a minimum of code. Here’s how to use jQuery on your site.

Here’s an example of some jQuery code:

Probably one of the most noticable things is that each line of code starts with dollar signs. These dollar signs are part of the jQuery syntax.

So the following two examples are equivalent:

No-Conflict Mode

Note that the dollar sign is not unique to jQuery. There are also other JavaScript libraries that also use a dollar sign. The dollar sign is simply a JavaScript identifier.

This could potentially lead to conflicts if you use another JavaScript library alongside jQuery. To avoid any conflicts, you can relinquish control of the dollar sign. This is referred to as «no-conflict mode».

You can put jQuery into no-conflict mode by inserting a line of code immediately after jQuery is loaded onto the page (and before you attempt to use jQuery in your page).

Just to be clear, under most circumstances, you won’t need to do this. You only need to do this if you want to relinquish the dollar sign as an alias to jQuery.

The ready() Method

Most jQuery code you encounter will probably be wrapped in one of the following (or some variation):

This is jQuery’s ready() method. This method allows you to run code as soon as the page’s Document Object Model (DOM) becomes safe to manipulate.

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.

You should still place your code inside the ready() method even if you wrap your code within an event handler (such as click() ). DOM objects still need to be loaded before attempting to apply event handlers against them.

The JavaScript Version

First, here they all are together:

The window.onload and load events will wait until everything has downloaded — even the stylesheets, images, banner ads, subframes etc.

The DOMContentLoaded only waits for the HTML document to be completely loaded and parsed, without waiting for stylesheets, images, banner ads, subframes etc to finish loading. Therefore, your code will typically run sooner than the window.onload and load events. This is usually a good thing, as images and banner ads tend to take longer to load than it takes to have the DOM ready.

jQuery’s ready() method only waits for the DOM to be ready also. However, there is an important difference that makes the jQuery option slightly more robust. According to the jQuery documentation:

Selectors

The basic concept of jQuery is, you select an element, then perform an action against that element.

Here are some examples:

jQuery uses selectors to select an element before applying an action to it.

In jQuery, the selector goes inside brackets and quotes. Like this:

You can also use more advanced selectors, such as these:

jQuery supports most CSS3 selectors and also some non-standard selectors.

Events

jQuery uses events to determine when a block of code should run.

Events are triggered when something happens within the DOM. Some events are triggered by user actions (such as the user clicks on an element, moves the mouse, etc), other events are triggered by the browser (such as the page has loaded, an animation has finished running, etc).

When you write jQuery/JavaScript, you need to specify when the code should run. If you don’t do this, then it will simply run when the browser loads it. Running a script as soon as the window loads isn’t always desirable. Most of the time you will only want the code to run once a certain event has occurred.

Here’s an example of attaching an event handler to a selection:

In this case, the code will run when the user clicks a button element.

The selector comes first (in this case button ), then the event handler (in this case click() ). A function is provided to the event handler, which is where you write your code (i.e. between the <> (curly braces)).

So we could combine that code with one of the previous examples, and we’d end up with this:

Here it is in action:

White Space

You can include white space within the brackets or leave it out. It doesn’t matter. For example, all of the examples are equivalent:

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *