Function of jQuery
After including jQuery in the project you are doing, you should find out how select the items in which it is present.
Be aware that jQuery can be passed with a bunch of arguments such as strings which contain CSS selectors. These selectors are useful for selecting HTML elements of behavior. So, if you want to select a paragraph for a page, you need to write jQuery (“p”) in your case app.js or script tag.
Here p is your CSS selector for selecting the paragraphs that you pass to “p” jQuery string. If you want to select all items with a class error, you need to write jQuery (“.error”); … Although you can fully use this method every time you need to choose HTML elements, please note there are other ways I can call it. For example, you can also use the abbreviation $. Using the examples above, you may use $ (“.error”) and $ (“p”)… Again, if you want the ultimate in speed and convenience, this is more ideal use $.
When you learn how to select items, you should know how to assign them their behavior. It’s easy to do this in jQuery. All you have to do is use the method you need for the behavior and put it in the last part elements. For example, if you want to hide certain paragraphs using the class error, you need to call hide () method.
To understand this better, consider the following example:
< p class = “ error “ > You cannot see this because it is hidden initially. < /p > < p > You can see this since it is not hidden like the first one. < /p > $ ( “ p.error “ ) .hide ( ) ;
In fact, everything is very simple. jQuery is built on the principle of least surprise. this the developers assumed that it would be so. So, if you want to show hidden elements, you must use show (). If you want to change the speed, for example few milliseconds from linear animation speed and using slow or quickly, you can also rely on jQuery.
For example, you want to slowly display the error message after hiding this is the first. To make this possible, you must write the following codes:
< p class = “error” > You cannot see this at first because it is hidden, but it is revealed eventually. < /p > < p > You can see this because it is not hidden. < /p > $ ( “ p.error “ ) .hide ( ) ; $ ( “ p.error “ ) .show ( “ slow “ ) ;
Like this. You now have effects on your site. How about keeping your codes DRY, which means “Don’t Repeat”? Yourself. With jQuery, you can chain methods. Still using in the above example you can change your codes and write the following instead:
$ ( “ p.error “ ) .hide ( ) .show ( “ slow “ ) ;
You may notice that the lines can get long at times, but in reality it is good thing as it helps to get fewer lines of code. In fact, it allows do more things without using many lines.