A collection of simple tips to help up your jQuery game.
For other great lists check out @sindresorhus's curated list of awesome lists.
noConflict()
.on()
Binding Instead of .click()
noConflict()
The $
alias used by jQuery is also used by other JavaScript libraries. To ensure that jQuery doesn't conflict with the $
object of different libraries, use the noConflict()
method at the start of the document:
jQuery.noConflict();
Now you'll reference the jQuery object using the jQuery
variable name instead of $
(e.g., jQuery('div p').hide()
). If you have multiple versions of jQuery on the same page (not recommended), you can use noConflict()
to set an alias to a specific version:
let $x = jQuery.noConflict();
<sup>back to table of contents</sup>
Before you can do anything with jQuery you first need to make certain it has loaded:
if (typeof jQuery == 'undefined') { console.log('jQuery hasn\'t loaded'); } else { console.log('jQuery has loaded'); }
Now you're off...
<sup>back to table of contents</sup>
Prior using a HTML element you need to ensure it's part of DOM.
if ($("#selector").length) { //do something with element }
<sup>back to table of contents</sup>
.on()
Binding Instead of .click()
Using .on()
gives you several advantages over using .click()
, such as the ability to add multiple events...
.on('click tap hover')
...a binding applies to dynamically created elements, as well (there's no need to manually bind every single element dynamically added to a DOM element)...
...and the possibility to set a namespace:
.on('click.menuOpening')
Namespaces give you the power to unbind a specific event (e.g., .off('click.menuOpening')
).
<sup>back to table of contents</sup>
By using the animate
and scrollTop
methods in jQuery you don't need a plugin to create a simple scroll-to-top animation:
// Back to top $('.container').on('click', '.back-to-top', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 800); });
<!-- Create an anchor tag --> <div class="container"> <a href="#" class="back-to-top">Back to top</a> </div>
Changing the scrollTop
value changes where you wants the scrollbar to land. All you're really doing is animating the body of the document throughout the course of 800 milliseconds until it scrolls to the top of the document.
[!NOTE] Watch for some buggy behavior with
scrollTop
.
<sup>back to table of contents</sup>
If your web page uses a lot of images that aren't visible initially (e.g., on hover) it makes sense to preload them:
$.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { $('<img>').attr('src', arguments[i]); } }; $.preloadImages('img/hover-on.png', 'img/hover-off.png');
<sup>back to table of contents</sup>
Sometimes you might need to check if your images have fully loaded in order to continue on with your scripts:
$('img').on('load', function () { console.log('image load successful'); });
You can also check if one particular image has loaded by replacing the <img>
tag with an ID or class.
<sup>back to table of contents</sup>
If you happen to find broken image links on your site replacing them one by one can be a pain. This simple piece of code can save a lot of headaches:
$('img').on('error', function () { if(!$(this).hasClass('broken-image')) { $(this).prop('src', 'img/broken.png').addClass('broken-image'); } });
Alternatively, if you wish to hide broken images this snippet will take care of that for:
$('img').on('error', function () { $(this).hide(); });
<sup>back to table of contents</sup>
jQuery AJAX methods are a common way to request text, HTML, XML, or JSON. If you wanted to send a form via AJAX you could collect the user inputs via the val()
method:
$.post('sign_up.php', { user_name: $('input[name=user_name]').val(), email: $('input[name=email]').val(), password: $('input[name=password]').val(), });
But all of those val()
calls are expensive and using .val()
on <textarea>
elements will strip carriage return characters from the browser-reported value. A better way of collecting user inputs is using the serialize()
function which collects them as a string:
$.post('sign_up', $('#sign-up-form').serialize());
<sup>back to table of contents</sup>
Let's say you want to change the visual of a clickable element on your page when a user hovers over it. You can add a class to your element when the user is hovering; when the user stops hovering removes the class:
$('.btn').on('hover', function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); });
You need to add the necessary CSS. If you want an even simpler way use the toggleClass
method:
$('.btn').on('hover', function () { $(this).toggleClass('hover'); });
[!NOTE] CSS may be a faster solution in this case but it's still worthwhile to know this.
<sup>back to table of contents</sup>
At times you may want the submit button of a form or one of its text inputs to be disabled until the user has performed a certain action (e.g., checking the "I've read the terms" checkbox). Add the disabled
attribute to your input so you can enable it when you want:
$('input[type="submit"]').prop('disabled', true);
All you need to do is run the prop
method again on the input, but set the value of disabled
to false
:
$('input[type="submit"]').prop('disabled', false);
<sup>back to table of contents</sup>
Sometimes you don't want links to go to a certain web page nor reload the page; you might want them to do something else like trigger another script. This will do the trick of preventing the default action:
$('a.no-link').on('click', function (e) { e.preventDefault(); });
<sup>back to table of contents</sup>
Think of how many times you write the same selector over and over again in any project. Every $('.element')
selector has to search the entire DOM each time, regardless if that selector had previously run. Instead you can run the selector once and store the results in a variable:
var blocks = $('#blocks').find('li');
Now you can use the blocks
variable wherever you want without having to search the DOM every time:
$('#hideBlocks').on('click', function () { blocks.fadeOut(); }); $('#showBlocks').on('click', function () { blocks.fadeIn(); });
Caching jQuery selectors is a good performance gain.
<sup>back to table of contents</sup>
Sliding and fading are common in animations with jQuery. You might want to show an element when a user clicks something, which makes the fadeIn
and slideDown
methods perfect, but if you want that element to appear on the first click and then disappear on the second, this will work fine:
// Fade $('.btn').on('click', function () { $('.element').fadeToggle('slow'); }); // Toggle $('.btn').on('click', function () { $('.element').slideToggle('slow'); });
<sup>back to table of contents</sup>
This is a simple method for a quick accordion:
// Close all panels $('#accordion').find('.content').hide(); // Accordion $('#accordion').find('.accordion-header').on('click', function () { var next = $(this).next(); next.slideToggle('fast'); $('.content').not(next).slideUp('fast'); return false; });
By adding this script all you really need to do on your web page is the necessary HTML to get this working.
<sup>back to table of contents</sup>
Sometimes you'll want two divs to have the same height no matter what content they have in them:
$('.div').css('min-height', $('.main-div').height());
This example sets the min-height
which means that it can be bigger than the main div but never smaller. However, a more flexible method would be to loop over a set of elements and set height
to the height of the tallest element:
var $columns = $('.column'); var height = 0; $columns.each(function () { if ($(this).height() > height) { height = $(this).height(); } }); $columns.height(height);
If you want all columns to have the same height:
var $rows = $('.same-height-columns'); $rows.each(function () { $(this).find('.column').height($(this).height()); });
[!NOTE] This can be done several ways in CSS but depending on what your needs are, knowing how to do this in jQuery is handy.
<sup>back to table of contents</sup>
Open external links in a new browser tab or window and ensure links on the same origin open in the same tab or window:
$('a[href^="http"]').attr('target', '_blank'); $('a[href^="//"]').attr('target', '_blank'); $('a[href^="' + window.location.origin + '"]').attr('target', '_self');
<sup>back to table of contents</sup>
By using the contains()
selector in jQuery you can find text in content of an element. If text doesn't exists, that element will be hidden:
var search = $('#search').val(); $('div:not(:contains("' + search + '"))').hide();
<sup>back to table of contents</sup>
Trigger JavaScript when the user is no longer focusing on a tab or refocuses on a tab:
$(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!'); } });
<sup>back to table of contents</sup>
When an AJAX call returns a 404 or 500 error, the error handler will be executed. If the handler isn't defined, other jQuery code might not work as intended. To define a global AJAX error handler:
$(document).on('ajaxError', function (e, xhr, settings, error) { console.log(error); });
<sup>back to table of contents</sup>
jQuery allows for the "chaining" of plugin method calls to mitigate the process of repeatedly querying the DOM and creating multiple jQuery objects. Let's say the following snippet represents your plugin method calls:
$('#elem').show(); $('#elem').html('bla'); $('#elem').otherStuff();
This could be vastly improved by using chaining:
$('#elem') .show() .html('bla') .otherStuff();
An alternative is to cache the element in a variable (prefixed with $
):
var $elem = $('#elem'); $elem.hide(); $elem.html('bla'); $elem.otherStuff();
Both chaining and caching methods in jQuery are best practices that lead to shorter and faster code.
<sup>back to table of contents</sup>
Let's say you end up with too many items in a list. Maybe the content is produced by a CMS and you want to order them alphabetically:
var ul = $('#list'), lis = $('li', ul).get(); lis.sort(function (a, b) { return ($(a).text().toUpperCase() < $(b).text().toUpperCase()) ? -1 : 1; }); ul.append(lis);
There you go!
<sup>back to table of contents</sup>
If you want to disable right-click, you can do it for an entire page...
$(document).ready(function () { $(document).bind('contextmenu', function (e) { return false; }) })
...and you can also do the same for a specific element:
$(document).ready(function () { $('#submit').bind('contextmenu', function (e) { return false; }) })
<sup>back to table of contents</sup>
Current versions of Chrome, Firefox, Safari, Opera, Edge, and IE11.
<sup>back to table of contents</sup>
<sup>[back to table of
字节跳动发布的AI编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分 析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号