Jquery tips (required) _ jquery-js tutorial

Source: Internet
Author: User
This article mainly introduces Jquery skills (must be mastered). For more information, see Check whether jQuery Loads

Before using jQuery for any operations, you need to confirm that it has been loaded:

if (typeof jQuery == 'undefined') {console.log('jQuery hasn\'t loaded');} else {console.log('jQuery has loaded');}

Back to Top button

Using the animate and scrollTop methods in jQuery, you can create a simple scroll up effect without the need for plug-ins:

// Return the top $ ('a. top '). click (function (e) {e. preventDefault (); $ (document. body ). animate ({scrollTop: 0}, 800 );});
 Back to top

Adjust the scrollTop value to change the rolling landing position. What you actually do is to constantly set the location of the document subject within 800 milliseconds until it scrolls to the top.

Preload Images

If your webpage uses a large number of images that are not immediately visible (for example, images triggered by hovering the mouse), it makes sense to preload these images:

$.preloadImages = function () {for (var i = 0; i < arguments.length; i++) {$('').attr('src', arguments[i]);}};

$.preloadImages('img/hover-on.png', 'img/hover-off.png');

Determine whether the image is loaded

In some cases, to continue executing the script, you need to check whether the image has been fully loaded:

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

Similarly, you can use a tag with the id or class attribute to check whether the image is loaded.

Automatic Repair of invalid Images

If you find invalid image links on your website, replacing them one by one will be tough. This simple code can greatly reduce the pain:

$('img').on('error', function () {if(!$(this).hasClass('broken-image')) {$(this).prop('src', 'img/broken.png').addClass('broken-image');}});

Even if you do not have any invalid links, adding this code will not cause any loss.

Hover the mouse over the class

If you want to change the visual effect of an element when you hover your mouse over it, you can add a class to the element when it is hovering, when the mouse is no longer hovering, remove this class:

$('.btn').hover(function () {$(this).addClass('hover');}, function () {$(this).removeClass('hover');});

If you are still looking for a simpler approach, you can use the toggleClass method, just add the necessary CSS:

$('.btn').hover(function () {$(this).toggleClass('hover');});

Note: In this case, using CSS may be a faster solution, but this method is worth a little understanding.

Disable input fields

Sometimes, you may want to disable the form submission button or disable an input box before the user completes a specific operation (for example, check the "I have read regulations" confirmation box. You can add the disabled attribute to your input field and enable it as needed:

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

You only need to run the prop method again on the input field, but change the disabled value to false this time:

$('input[type="submit"]').prop('disabled', false);

Block link Loading

Sometimes you do not want to link to a specified page or reload the current page, but want them to do something else, such as triggering other scripts. This requires some articles on blocking default actions:

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

Cache jQuery Selector

Think about how many identical selectors you have written in the project again and again. Each $ ('. element') must query the entire DOM once, whether or not it has been executed like this. Instead, we only run the selector once and store the result in a variable:

var blocks = $('#blocks').find('li');

Now you can use the blocks variable anywhere without having to query the DOM every time:

$('#hideBlocks').click(function () {blocks.fadeOut();});$('#showBlocks').click(function () {blocks.fadeIn();});

Cached jQuery selector is a simple performance improvement.

Switch fade-out/slide

Fade-out and slide are a lot of the effects we use in jQuery. You may only want to display an element after a user clicks it. In this case, the fadeIn and slideDown methods are perfect. However, if you want this element to appear when you click it for the first time and disappear when you click it again, this code is useful:

// Fade out $ ('. btn '). click (function () {$ ('. element '). fadeToggle ('low') ;}); // switch $ ('. btn '). click (function () {$ ('. element '). slideToggle ('slow ');});

Simple accordion Effect

This is a simple method to quickly implement the accordion effect:

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

By adding this script, you only need to provide the necessary HTML elements so that it can run normally.

Enable two equal p values

Sometimes you want to have the same height no matter what each p contains:

$('.p').css('min-height', $('.main-p').height());

In this example, min-height is set, which means that the height can be greater than the primary p but not smaller than it. However, a more flexible method is to traverse a group of elements and set the height to the highest element height:

var $columns = $('.column');var height = 0;$columns.each(function () {if ($(this).height() > height) {height = $(this).height();}});$columns.height(height);

If you want the heights of all columns to be the same:

var $rows = $('.same-height-columns');$rows.each(function () {$(this).find('.column').height($(this).height());});

Open external link in new tab/window

Open an external link on a new browser tab or window and make sure that the link of the same source is opened on the same tab or window:

$('a[href^="http"]').attr('target', '_blank');$('a[href^="//"]').attr('target', '_blank');$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

Note: window. location. origin is unavailable in IE10. This solution focuses on this issue.

Search for elements by text

By using the contains () selector of jQuery, you can find the text in the element content. If the text does not exist, the element is hidden:

var search = $('#search').val();$('p:not(:contains("' + search + '"))').hide();

Triggered when the visibility attribute changes

When the user's focus leaves or returns to a tab again, the following error occurs:

$(document).on('visibilitychange', function (e) {if (e.target.visibilityState === "visible") {console.log('Tab is now in view!');} else if (e.target.visibilityState === "hidden") {console.log('Tab is now hidden!');}});

Ajax call error handling

When an Ajax call returns a 404 or 500 error, the error handler is executed. If error handling is not defined, other jQuery code may no longer be valid. So define a global Ajax error handling:

$(document).ajaxError(function (e, xhr, settings, error) {console.log(error);});

Chained plug-in call

JQuery allows the method called by the "chained" plug-in to ease the process of repeatedly querying DOM and creating multiple jQuery objects. For example, the following code indicates your plug-in call:

$('#elem').show();$('#elem').html('bla');$('#elem').otherStuff();

Through the use of chain operations, there has been a significant improvement:

$('#elem').show().html('bla').otherStuff();

Another method is to cache the elements in the variable (prefixed with $:

var $elem = $('#elem');$elem.hide();$elem.html('bla');$elem.otherStuff();

Chain Operations and cache elements are the best practices in jQuery to simplify and optimize code.

Some simple tips are collected here to help you use jQuery.

Check whether jQuery Loads

Before using jQuery for any operations, you need to confirm that it has been loaded:

if (typeof jQuery == 'undefined') {console.log('jQuery hasn\'t loaded');} else {console.log('jQuery has loaded');}

Back to Top button

Using the animate and scrollTop methods in jQuery, you can create a simple scroll up effect without the need for plug-ins:

// Return the top $ ('a. top '). click (function (e) {e. preventDefault (); $ (document. body ). animate ({scrollTop: 0}, 800 );});
 Back to top

Adjust the scrollTop value to change the rolling landing position. What you actually do is to constantly set the location of the document subject within 800 milliseconds until it scrolls to the top.

Preload Images

If your webpage uses a large number of images that are not immediately visible (for example, images triggered by hovering the mouse), it makes sense to preload these images:

$.preloadImages = function () {for (var i = 0; i < arguments.length; i++) {$('').attr('src', arguments[i]);}};$.preloadImages('img/hover-on.png', 'img/hover-off.png');

Determine whether the image is loaded

In some cases, to continue executing the script, you need to check whether the image has been fully loaded:

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

Similarly, you can use a tag with the id or class attribute to check whether the image is loaded.

Automatic Repair of invalid Images

If you find invalid image links on your website, replacing them one by one will be tough. This simple code can greatly reduce the pain:

$('img').on('error', function () {if(!$(this).hasClass('broken-image')) {$(this).prop('src', 'img/broken.png').addClass('broken-image');}});

Even if you do not have any invalid links, adding this code will not cause any loss.

Hover the mouse over the class

If you want to change the visual effect of an element when you hover your mouse over it, you can add a class to the element when it is hovering, when the mouse is no longer hovering, remove this class:

$('.btn').hover(function () {$(this).addClass('hover');}, function () {$(this).removeClass('hover');});

If you are still looking for a simpler approach, you can use the toggleClass method, just add the necessary CSS:

$('.btn').hover(function () {$(this).toggleClass('hover');});

Note: In this case, using CSS may be a faster solution, but this method is worth a little understanding.

Disable input fields

Sometimes, you may want to disable the form submission button or disable an input box before the user completes a specific operation (for example, check the "I have read regulations" confirmation box. You can add the disabled attribute to your input field and enable it as needed:

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

You only need to run the prop method again on the input field, but change the disabled value to false this time:

$('input[type="submit"]').prop('disabled', false);

Block link Loading

Sometimes you do not want to link to a specified page or reload the current page, but want them to do something else, such as triggering other scripts. This requires some articles on blocking default actions:

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

Cache jQuery Selector

Think about how many identical selectors you have written in the project again and again. Each $ ('. element') must query the entire DOM once, whether or not it has been executed like this. Instead, we only run the selector once and store the result in a variable:

var blocks = $('#blocks').find('li');

Now you can use the blocks variable anywhere without having to query the DOM every time:

$('#hideBlocks').click(function () {blocks.fadeOut();});$('#showBlocks').click(function () {blocks.fadeIn();});

Cached jQuery selector is a simple performance improvement.

Switch fade-out/slide

Fade-out and slide are a lot of the effects we use in jQuery. You may only want to display an element after a user clicks it. In this case, the fadeIn and slideDown methods are perfect. However, if you want this element to appear when you click it for the first time and disappear when you click it again, this code is useful:

// Fade out $ ('. btn '). click (function () {$ ('. element '). fadeToggle ('low') ;}); // switch $ ('. btn '). click (function () {$ ('. element '). slideToggle ('slow ');});

Simple accordion Effect

This is a simple method to quickly implement the accordion effect:

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

By adding this script, you only need to provide the necessary HTML elements so that it can run normally.

Enable two equal p values

Sometimes you want to have the same height no matter what each p contains:

$('.p').css('min-height', $('.main-p').height());

In this example, min-height is set, which means that the height can be greater than the primary p but not smaller than it. However, a more flexible method is to traverse a group of elements and set the height to the highest element height:

var $columns = $('.column');var height = 0;$columns.each(function () {if ($(this).height() > height) {height = $(this).height();}});$columns.height(height);

If you want the heights of all columns to be the same:

var $rows = $('.same-height-columns');$rows.each(function () {$(this).find('.column').height($(this).height());});

Open external link in new tab/window

Open an external link on a new browser tab or window and make sure that the link of the same source is opened on the same tab or window:

$('a[href^="http"]').attr('target', '_blank');$('a[href^="//"]').attr('target', '_blank');$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

Note: window. location. origin is unavailable in IE10. This solution focuses on this issue.

Search for elements by text

By using the contains () selector of jQuery, you can find the text in the element content. If the text does not exist, the element is hidden:

var search = $('#search').val();$('p:not(:contains("' + search + '"))').hide();

Triggered when the visibility attribute changes

When the user's focus leaves or returns to a tab again, the following error occurs:

$(document).on('visibilitychange', function (e) {if (e.target.visibilityState === "visible") {console.log('Tab is now in view!');} else if (e.target.visibilityState === "hidden") {console.log('Tab is now hidden!');}});

Ajax call error handling

When an Ajax call returns a 404 or 500 error, the error handler is executed. If error handling is not defined, other jQuery code may no longer be valid. So define a global Ajax error handling:

$(document).ajaxError(function (e, xhr, settings, error) {console.log(error);});

Chained plug-in call

JQuery allows the method called by the "chained" plug-in to ease the process of repeatedly querying DOM and creating multiple jQuery objects. For example, the following code indicates your plug-in call:

$('#elem').show();$('#elem').html('bla');$('#elem').otherStuff();

Through the use of chain operations, there has been a significant improvement:

$('#elem').show().html('bla').otherStuff();

Another method is to cache the elements in the variable (prefixed with $:

var $elem = $('#elem');$elem.hide();$elem.html('bla');$elem.otherStuff();

Chain Operations and cache elements are the best practices in jQuery to simplify and optimize code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.