jQuery: A comprehensive beginner’s guide to jQuery [2 ed.]

752 160 543KB

English Pages [160]

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

jQuery: A comprehensive beginner’s guide to jQuery [2 ed.]

Citation preview

JavaScript and JQuery The Ultimate Beginner's Guide to Learn JavaScript and JQuery Step by Step

By John Bach

1nd Edition

"Programming isn't about what you know; it's about what you can figure out.” - Chris Pine

Memlnc.com

INTRODUCTION

8

EXAMPLE

8

THE SYNTAX DIFFERENCE

9

JAVASCRIPT BASICS AND COMMON ERRORS COMMITTED BY BEGINNERS 9 NOTE ON COMMENTS

11

THE CORE COMPONENTS OF JAVASCRIPT

12

VARIABLES

12

FUNCTIONS

13

FUNCTIONS AND VARIABLE SCOPE

15

OBJECTS

18

ACCESS TO PROPERTIES

19

OBJECTS IN JQUERY

26

MORE DETAILS

27

ARRAYS

27

FOR LOOPS: LIST THE ARRAYS LOGIC AND VALIDATION

29

29

LOGICAL OPERATORS TERNARY OPERATOR JAVASCRIPT BUGS NAME THINGS RESERVED WORDS OPERATIONS ON NUMBERS AND STRINGS

32 33 34 34 35 36

CHAPTER I……………………………………………………………………….38 JQUERY BASICS

38

WHAT IS THIS SYMBOL: $? ACCESS TO ITEMS

38 41

OTHER WAYS TO CREATE A JQUERY OBJECT

41

DOES YOUR SELECTION CONTAIN ANY ELEMENTS?

42

ACCESS INDIVIDUAL ITEMS FROM A SELECTION CREATE NEW OBJECTS

43 44

DEALING WITH SELECTIONS

45

IDENTIFICATION CHECK CHAIN (CHAINING) CONCLUSION

46 48 50

CHAPTER II …………………………………………………………………….50 JQUERY LEARN PAGE NAVIGATION AND EDITING FUNCTIONS IN JQUERY 50 TRAVERSAL FILTER SELECTIONS

51 51

FIND ITEMS STARTING WITH A SELECTION

52

RETURN TO THE ORIGINAL SELECTION

54

MANIPULATION OF ELEMENTS EDIT ITEMS

56 56

ADD OR DELETE CLASSES

57

CHANGE OF APPEARANCE

58

CHANGING THE VALUES OF FORMS

59

CHANGE OTHER ATTRIBUTES

61

GET INFORMATION FROM THE ELEMENTS ADD ITEMS TO THE PAGE COPY ITEMS DELETE ITEMS CONCLUSION

61 62 64 65 67

CHAPTER III …………………………………………………………………..68 JQUERY EVENTS AND HOW TO DELEGATE THEM

68

CONFINE THE EVENTS WITHIN THE NAMESPACE

71

CONNECT MULTIPLE EVENTS SIMULTANEOUSLY

72

PASS THE FUNCTIONS NAMED EVENTS

73

EVENT OBJECT

74

INSIDE THE SPONSORS

74

PREVENTING INITIAL BEHAVIOR

75

EVENT BUBBLING

76

EVENT DELEGATION

77

CONCLUSION

79

CHAPTER IV…………………………………………………………………… MOVE THE PAGE WITH JQUERY

79

EFFECTS INCLUDED WITH JQUERY

80

CUSTOM EFFECTS USING .ANIMATE ()

83

MOVEMENT MANAGEMENT

85

CHAPTER V…………………………………………………………………. INTRODUCED TO AJAX AND DEFERRED OBJECTS ON JQUERY

85

AJAX

85

$ .AJAX

86

A IN AJAX MEANS "ASYNCHRONOUS"

88

X IN AJAX MEANS JSON! SHORT FUNCTIONS SUBMIT DATA AND WORK WITH FORMS

79

89 91 92

85

JQXHR

93

JSONP

95

DEFERRED OBJECTS

97

$ .DEFERRED

97

.PIPE ()

99

DEALING WITH OPERATIONS THAT MAY BE ASYNCHRONOUS 100

CHAPTER V…………………………………………………………

103

HOW TO CREATE A MOVEABLE SLIDESHOW WITH JQUERY 103 EXPLAIN THE STEPS IN THIS LESSON FOR CREATING A JAVASCRIPT SLIDE SHOW 104 NOW LET'S LOOK AT CSS STYLES

107

FINALLY, LET'S LOOK AT JQUERY FUNCTIONS

109

CHAPTER VII…………………………………………………………

111

10 JQUERY TRICKS THAT EVERY DESIGNER SHOULD KNOW 111 BACK TO TOP BUTTON CHECK UPLOAD PHOTOS CORRECT DAMAGED PHOTOS AUTOMATICALLY SUBSTITUTION OF THE VARIETY WHEN HOVER

112 113 113 114

DISABLE INPUT FIELDS

114

STOP DOWNLOADING LINKS

115

SWITCH BETWEEN FADE AND SLIDE COSPLAY

115

FOLDING EFFECT

116

DETERMINE THE HEIGHT OF THE DIV ELEMENT DEPENDING ON THE POST 116 LIST OF DIFFERENT COLORS ACCORDING TO THE EVEN AND ODD ELEMENTS 117 CHAPTER VIII …………………………………………………….. 117

HEADERS AND STATIC COLUMN HTML TABLES WITH JQUERY 117 SOLVE CSS USING POSITION: STICKY?

118

SOLVE USING JQUERY

118

WHAT ARE WE TRYING TO ACCOMPLISH? CSS TO GET STARTED USING JAVASCRIPT STEP 1: COPY THE ELEMENT STEP 2: ENCAPSULATE AND COPY THE TABLE

119 120 122 123 123

STEP 3: SETTING THE CONTENT OF THE COPIED TABLES 124 STEP 4: FUNCTIONS

125

STEP 5: CONNECT EVERYTHING

131

THE DEBATE

132

USE POSITION: FIXED

133

USE POSITION: STICKY

133

MEM T

Introduction

jQuery works by using functions, a library, written in JavaScript. You can use these functions to write powerful things without actually typing much code. jQuery is very lightweight and efficient so you don’t have to worry about it slowing down the user experience.

Referencing jQuery is extremely easy and there are multiple ways to do it. Remember that you can reference JavaScript from anywhere. You could even take the JavaScript that I am writing for this website and use it. The first way uses this principle. Google has a jQuery library available for all developers to use.

Example







  • Slide 1
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5




By looking carefully at the codes above you will notice that the HTML codes for your display pages start with Doctype, the title of the link and a link to the CSS style file. After these three, you will find that to prepare and run the slide show, a link has been added for the two previously mentioned LocalScroll and ScrollTo, jQuery library and script.js file. The HTML codes responsible for creating the slideshow are also divided into two parts: a div tag is defined as slideshow and another is a slideshow-nav. It is important to note here that the div tag identified by slideshow will contain an unnumbered list of related images, and li tags contain identifiers that are compatible with slideshow-nav links.

Now let's look at CSS styles css / style.css

#slideshow {/ * slider container css * / width: 800px; height: 400px; overflow: hidden; margin: 50px auto 50px auto; box-shadow: 0px 0px 50px # 333; -moz-box-shadow: 0px 0px 50px # 333; -webkit-box-shadow: 0px 0px 50px # 333; }

#slideshow ul {/ * manage slider scroll elements css * / width: 4000px; list-style: none; }

#slideshow ul li { float: left; }

The CSS styles above will convert the simple look generated by HTML code into pages that look similar to the desired slideshow. This is done starting with defining the height and width of these slides, also specifying the dimensions to be exactly the same as the dimensions of the photo slides. With all slides floating side by side, it is possible to define the total width measurements for the unnumbered list up to 4590px. The overflow feature was also used to prevent multiple images from appearing entirely on the page. All you need to do here is to simply set the overflow feature as overflow: scroll, this setting allows slideshows to display even when there is no JavaScript. A nice shade was added using the CSS3-box shadow as shown below

# slideshow-nav {/ * Slider navigation container css * / width: 150px; margin: 0 auto 100px auto; } # slideshow-nav ul { list-style: none; } # slideshow-nav ul li { float: left; } # slideshow-nav ul li a {/ * navigation styling css * / display: block; width: 20px; height: 20px; float: left; margin: 0 5px; background: #fff; text-indent: -9999px; border-radius: 50%; -webkit-border-radius: 50%; box-shadow: 0px 0px 30px # 000; -webkit-box-shadow: 0px 0px 30px # 000; } # slideshow-nav ul li a: hover, # slideshow-nav ul li a.active { / * hover and active navigation css * / background: # 333; }

With a careful preview here, we will notice that the div tag, which is defined as slideshow-nav, has been moved to a position below the main section for the slide show. We also don't want multiple buttons in the slide show that don't work when JavaScript functionality is enabled. You can use visibility: hidden to hide these buttons by default, which makes it possible to show them at a later time. You may also be interested in knowing that the links for each navigation menu have been converted to circular buttons with the help of border-radius in CSS3 with the default text offsets from the screen by setting a negative value for text-indent. So far, the slide show works tangibly and without the need for JavaScript. There is only a navigation bar that allows the user to move back and forth between different images.

Finally, let's look at jQuery functions js / custom-scripts.js

$ (document) .ready (function () { var slider = $ ("# slideshow"); var slider_nav = $ ("# slideshow-nav"); slider_nav.find ("a [href = # slide1]"). addClass ("active");

slider_nav.localScroll ({ target: '# slideshow', axis: 'x' });

slider_nav.find ("a"). click (function () { slider_nav.find ("a"). removeClass ("active"); $ (this) .addClass ("active"); }); });

If you look at the code above, you will see that the slideshow CSS styles have been changed from overflow: scroll to overflow: hidden to remove the slider. After that the nav buttons are set to be visible with the active category automatically added to the first button. Both extensions are also enabled: LocalScroll and ScrollTo, in addition to applying LocalScroll functionality to slideshow-nav elements by directing those elements to target slideshow elements by moving along the X axis. Finally, to ensure that all buttons in the slide show work with their active category (whenever they were clicked), we will use a simple jQuery rule that will remove the active category from the buttons that were not clicked. This active category selected will appear within CSS styles to display only a gray background color to the clicked button. By doing a quick test on your browser, a fully functional JavaScript slideshow will appear....

Chapter VII 10 jQuery tricks that every designer should know JQuery is one of the most used libraries to add to pages, as it makes working with the Document object model, DOM easy.

There is no doubt that ease of dealing is a main reason for the popularity of jQuery, as it seems it is possible to do anything we want through this library.

There are, among our options, snippets that make it appear again and again. In this article, we will introduce ten provinces that everyone will use, from beginner to proficient, over and over again.

Back to top button // Back to top $ ('a.top'). click (function () { $ (document.body) .animate ({scrollTop: 0}, 800); return false; });

// Anchor tag Create a tag for the linker Back to top

Obviously, we don't need to add a Plugin for jQuery in order to get an easy move up; just use the animate and scrollTop functions.

The position of the scroll bar can be changed by changing the value of the scrollTop. In the example above we used the value 0 because we wanted to go back to the top of the page, but if we wanted an offset of 100px this value could be included.

What we did is move the Document body around 800 milliseconds until it reaches the top.

Check upload photos $ ('img'). load (function () { console.log ('image load successful'); });

Sometimes you need to make sure that all images are loaded before completing the script; the above three lines perform this task easily. You can also verify that a specific image has been uploaded by replacing the tag tag with ID or Class.

Correct damaged photos automatically $ ('img'). error (function () { $ (this) .attr ('src', 'img / broken.png'); });

Sometimes there is trouble in the image links on the site. It is difficult to change the links manually. The above clip automatically replaces the damaged images which saves a lot of problems.

Substitution of the variety when Hover $ ('. btn'). hover (function () { $ (this) .addClass ('hover'); }, function () { $ (this) .removeClass ('hover'); } );

We usually want to change the appearance of clickable items on a web page when the cursor hovers around them, which is exactly what the lines in the section above do; it adds an item to the item when hovering around it and then removes the item when the user stops. All you have to do is add the desired format into your CSS file.

Disable input fields $ ('input [type = "submit"]'). attr ("disabled", true);

You may want to disable the submit button or input field until the user performs a specific action (check the “I read terms” box, for example). The clip adds a disabled feature to the field, allowing you to enable it whenever you want. All you need to do to activate the field is to execute the removeAttr function with the disabled parameter passed as follows:

$ ('input [type = "submit"]'). removeAttr ("disabled");

Stop downloading links $ ('a.no-link'). click (function (e) { e.preventDefault (); });

We may wish the links to perform actions other than going to a page or even reloading it, which is what the lines above work on by disabling the default action. The reason, for example, might be another script activation.

Switch between Fade and Slide cosplay // Evanescence

$ (". btn"). click (function () { $ (". element"). fadeToggle ("slow"); });

// Switch $ (". btn"). click (function () { $ (". element"). slideToggle ("slow"); });

The fade and slippage effect is one of the most common effects in jQuery. When we only want to display an object on click, the fadeIn and slideDown functions are completely appropriate. But if we want the item to appear after the first click and then disappear after the second, this clip will do the job successfully.

Folding effect // Close all panels $ ('# accordion'). find (‘. content’). hide (); // The folding effect $ ('# accordion'). find ('. accordion-header'). click (function () { var next = $ (this) .next (); next.slideToggle ('fast'); $ ('. content'). not (next) .slideUp ('fast'); return false; });

All you need besides this section is the right HTML for impact. First we turn off all panels, then when the click event occurs, the associated header-related content slides sequentially. This is an easy way to get a collapsing effect quickly.

Determine the height of the div element depending on the post $ ('. div'). css ('min-height', $ ('. main-div'). height ());

This method enables the div to be set to the same height regardless of their content. On the above line set the height of the div elements so that they have at least the height of the main-div element.

List of different colors according to the even and odd elements $ ('li: odd'). css ('background', '# E8E8E8');

This line gives a background with the specified color for the individual elements of the list, enabling you to obtain a chart list - such as the zebra body - by adding a default background color in a CSS file that the even elements from the list take. This method is not limited to regulations, but extends to tables, divs, and others.

Chapter VIII Headers and static column html tables with jQuery Fixed schedule headers are not new in websites. Unlike paper, the reader can quickly shift his view to the top of the screen to know which column it is, but the dimensions of the screen make reading long tables difficult.

Fixed table headers, as its name indicates, remain fixed at the top of the table even if we go further into the table. The command helps keep the column names always close at hand, so that the user is not forced to go back to the top of the table every time for the look and then back again.

There are many jQuery scripts and add-ons that work in an effective and error-free manner, they are not the ideal solution for all possible problems, in some cases, the tables have to follow the rules of structuring for which additions are not calculated, such as tables that allow the scroll indicator to appear when it is not Enough space to show the table.

This article will not be the ideal solution for all situations, but it will be a solution to most common problems.

Solve CSS using position: sticky? CSS has an appropriate solution to this problem and is using postion: sticky. Unfortunately, the solution is not supported in chrome although it was previously supported, but the development team completely removed the feature from it for an unknown period. Because we cannot sacrifice all of the chrome users, we have to work around the problem.

Solve using jQuery JQuery's solution is very simple, but before we start using it, we have to take a look at how a table is correctly structured:















What are we trying to accomplish? We will try to make the script support most of the common problems which are:

Basic use: the table header is fixed. - Horizontal and vertical table headers. Broad tables:

* Horizontal column: If there are too many columns that cannot be shown in page width, we will use a fixed side column. * Vertical row: It is the primary use, that the upper head be fixed when going down the table. * Both columns: where we fix both the column and the row.

CSS to get started Although we will be using a solution via JavaScript, CSS is necessary in order to execute the command: .sticky-wrap { overflow-x: auto; position: relative; margin-bottom: 1.5em; width: 100%; } .sticky-wrap .sticky-thead, .sticky-wrap .sticky-col, .sticky-wrap .sticky-intersect { opacity: 0; position: absolute; top: 0; left: 0; transition: all .125s ease-in-out; z-index: 50; width: auto; / * Prevent table from stretching to full size * / } .sticky-wrap .sticky-thead { box-shadow: 0 0.25em 0.1em -0.1em rgba (0,0,0, .125); z-index: 100; width: 100%; / * Force stretch * / } .sticky-wrap .sticky-intersect { opacity: 1; z-index: 150; } .sticky-wrap .sticky-intersect th { background-color: # 666; color: #eee; } .sticky-wrap td, .sticky-wrap th { box-sizing: border-box;

}

Note: It is very important to move all of the CSS for the tag to sticky-wrap. This is so we can control it directly via jQuery.

Let's say you have the following CSS:

table { margin: 0 auto 1.5em; width: 75%; }

All you have to do is simply move it to sticky-wrap. :

.sticky-wrap { overflow-x: auto; / * Allows wide tables to overflow its containing parent * / position: relative; margin: 0 auto 1.5em; width: 75%;

}

Using Javascript We will implement our function on every table on the page. More importantly, we will check if the table has and if the latter contains at least one
. If the conditions are not met, our function will ignore this table.

$ (function () { // Here we select all tables on the page // But you are free to specify the tables you want $ ('table'). each (function () { if ($ (this) .find ('thead'). length> 0 && $ (this) .find ('th'). length> 0) { // The rest of the script will be here } }); });

Step 1: Copy the element // Define variables and some shortcuts var $ t = $ (this), $ w = $ (window), $ thead = $ (this) .find ('thead'). clone (), $ col = $ (this) .find ('thead, tbody'). clone ();

Step 2: Encapsulate and copy the table In order to support cases where the table is wider than what is permitted (i.e. when it is when a large number of columns, or long columns, we fold the table in so that we allow you to be scrollable on the horizontal axis: // Contain table $t .addClass ('sticky-enabled') .css ({ margin: 0, width: '100%'; }) .wrap ('');

// Check if we have specified that the table be scrolling along the horizontal axis if ($ t.hasClass ('overflow-y')) $ t.removeClass ('overflow-y'). parent (). addClass ('overflow-y');

// Create a new table header with a .stiky-head class $ t.after ('')

// If contains
we create a new column so that the cell is above the table if ($ t.find ('tbody th'). length> 0) { $ t.after ('
'); } // Shortcuts var $ stickyHead = $ (this) .siblings ('. sticky-thead'), $ stickyCol = $ (this) .siblings ('. sticky-col'), $ stickyInsct = $ (this) .siblings ('. sticky-intersect'), $ stickyWrap = $ (this) .parent ('. sticky-wrap');

Step 3: Setting the content of the copied tables What we will do now is take the copied content from the original table and put it in the new tables which will be attached:

The new table header will receive all of the content from the copied element. Conjoined columns will receive content from the first ' );

Step 4: Functions Here comes the most important part of our script, we will determine which functions must be implemented in order for the script to work properly:

Function for determining the width of
element of and all remaining elements from . Merging the column with the row (i.e. the column-row common cell) will take content through the top column to the right of the table (assuming we are dealing with the page on RTL basis).

// StickyHead gets content from

$ stickyHead.append ($ thead);

$ stickyCol .append ($ col) .find ('thead th: gt (0)'). remove () .end () .find ('tbody td'). remove ();

// StickyIntersect gets content from
in

$ stickyInsct.html ('
' + $ t.find ('thead th: first-child'). html () + '
elements in the header of a copied table, since we just copied the element, the width of the copied header will not be the actual header width, because the width of was not added since we don't know whether it will affect the header Page or not. Function for locating the fixed header position so that we update the horizontal copied header dimension, which we set position: absolute when we begin to pass the progress bar within the table. Function for locating the static side column and having the same header installation status.

A function to calculate the remaining space, and we will explain this function later in more depth.

// Function 1: setWidths () // Purpose: To set width of individually cloned element var setWidths = function () { $t .find ('thead th'). each (function (i) { $ stickyHead.find ('th'). eq (i) .width ($ (this) .width ()); }) .end () .find ('tr'). each (function (i) { $ stickyCol.find ('tr'). eq (i) .height ($ (this) .height ()); });

// Set width of sticky table head $ stickyHead.width ($ t.width ());

// Set width of sticky table col

$ stickyCol.find ('th'). add ($ stickyInsct.find ('th')). width ($ t.find ('thead th'). width ())

}, // Function 2: repositionStickyHead () // Purpose: To position the cloned sticky header (always present) appropriately repositionStickyHead = function () { // Return value of calculated allowance var allowance = calcAllowance ();

// Check if wrapper parent is overflowing along the y-axis if ($ t.height ()> $ stickyWrap.height ()) { // If it is overflowing // Position sticky header based on wrapper's scrollTop () if ($ stickyWrap.scrollTop ()> 0) { // When top of wrapping parent is out of view $ stickyHead.add ($ stickyInsct) .css ({ opacity: 1, top: $ stickyWrap.scrollTop () }); } else { // When top of wrapping parent is in view $ stickyHead.add ($ stickyInsct) .css ({ opacity: 0, top: 0 }); } } else { // If it is not overflowing (basic layout) // Position sticky header based on viewport scrollTop () if ($ w.scrollTop ()> $ t.offset (). top && $ w.scrollTop () 0) { // When left of wrapping parent is out of view // Show sticky column and intersect $ stickyCol.add ($ stickyInsct) .css ({ opacity: 1, left: $ stickyWrap.scrollLeft () }); } else { // When left of wrapping parent is in view // Hide sticky column but not the intersect // Reset left position $ stickyCol .css ({opacity: 0}) .add ($ stickyInsct) .css ({left: 0}); } }, // Function 4: calcAllowance () // Purpose: Return value of calculated allowance calcAllowance = function () { var a = 0;

// Get sum of height of last three rows $ t.find ('tbody tr: lt (3)'). each (function () { a + = $ (this) .height (); });

// Set fail safe limit (last three row might be too tall) // Set arbitrary limit at 0.25 of viewport height, or you can use an arbitrary pixel value if (a> $ w.height () * 0.25) { a = $ w.height () * 0.25; }

// Add height of sticky header itself a + = $ sticky.height ();

return a; }; }

Now we are going to explain what we did in the fourth function, we do not want the head of the table to append us to the bottom of the table, it is not necessary and may cover us the last line of the table, so it is necessary to keep an empty space at the bottom.

According to what I tried, I discovered that we don't need the header of the table when we get to the last 3 lines of the table because our focus has shifted to the content now.

$ t.find ('tbody tr: lt (4)'). each (function () { allowance + = $ (this) .height (); });

Step 5: Connect everything Now that we have finished defining all the necessary functions, all that remains is to link the event handlers with the $ window window.

When the DOM is ready, we make the initial calculations for the presentation. When you hold all of the information we calculate the dimensions again, this step is important because your table may contain objects carrying after the DOM such as images and web fonts. When scrolling in the main container but this will happen if the content is greater than the width of the container, then we want to reposition the main column. When the browser window is minimized, we want to recalculate the view. When going down in the browser we want to change the header of the table.

What we have just said can be summarized in the following code. Note that miniaturization and scrolling events are controlled with the addition of throttle + debounce. // # 1: DOM when ready setWidths ();

// # 2: We monitor the container in the event of a pass in it $ t.parent ('. sticky-wrap'). scroll ($. throttle (250, function () { repositionStickyHead (); repositionStickyCol (); }));

// Now we link what we made to the $ (window) element $w // # 3: When all the contents are loaded .load (setWidths) // # 4: When the window is minimized

// We have used throttle here so that the event does not fire more than once (by default the event is fired for each minimized part, here we wait until the reduction is complete and then we launch) .resize ($. throttle (250, function () { setWidths (); repositionStickyHead ();

repositionStickyCol (); }) // # 5: When going down in the window // We used throttle so the function doesn't launch much .scroll ($. throttle (250, repositionStickyHead);

And here we were!

The debate We know that nothing is perfect, so we will discuss other methods that have advantages over this method and its disadvantages and we have not used this method.

Use position: fixed Using this method may seem tempting for two reasons:

No calculations are required for the header of the table, because the fixed element is outside the physical page and will remain in place. We avoid slow calculations because the fixed elements chase the table and do not stick with it, because we do the calculation in fixed periods (via throttle) and therefore it will appear that the fixed element is unresponsive and therefore not normal.

But the problem with this method is that we remove the element from the page luster. If the table width exceeds the permissible width and it becomes necessary to add a scroll, a header will not append the content on the horizontal axis because it is fixed on the page. This is a great reason we are not allowed to use most jQuery plugins that offer these features. And I wrote this course to fix exactly this.

Use position: sticky The new feature is appropriate for the matter, in fact I built it for this matter in mind, the problem is that it is not supported by the chrome browser (previously it was supported but the support was completely removed) and thus lose all visitors from this browser.