18 great jQuery snippets
- 2020-09-16 07:20:36
- OfStack
1. Smooth scrolling of internal links implemented by jQuery
You don't need to use a complex plug-in, just download this code to achieve smooth scrolling based on internal links
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var anchor = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = anchor;
});
});
2. Use jQuery to get all nodes
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
3. Limit the number of selection boxes
$("#categories option").click(function(e){
if ($(this).parent().val().length < 2) {
$(this).removeAttr("selected");
}
});
4. jQuery USES wildcards to delete class
var _c = 'your-icon-class'
$('.currency').removeClass (function (index, css) {
return (css.match (/\bicon-\S+/g) || []).join(' ');
}).addClass('icon-'+_c);
5. Toggle enabled and disabled
/* HTML
|
|
<input type="text" value=" Welcome to visit www.admin10000.com" /><input type="button" value=" Disable the button " />
|
|
*/
// Plugin
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled');
else $this.attr('disabled', 'disabled');
});
};
})(jQuery);
// TEST
$(function () {
$('input:button').click(function () {
$('input:text').toggleDisabled();
});
});
Smooth scrolling back to the top
<h1 id="anchor">admin10000.com</h1>
<a class="topLink" href="#anchor"> Return to the top </a>
$(document).ready(function () {
$("a.topLink").click(function () {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});
7. Use jQuery and Google Analytics to track forms
var array1 = [];
$(document).ready(function () {
$('input').change(function () {
var formbox = $(this).attr('id');
array1.push(formbox);
console.log("you filled out box " + array1);
});
$('#submit').click(function () {
console.log('tracked ' + array1);
//alert('this is the order of boxes you filled out: ' + array1);
_gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
});
});
8, super simple password strength tips
$('#pass').keyup(function (e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');
} else {
$('#passstrength').className = 'error';
$('#passstrength').html('Weak!');
}
return true;
});
9. jQuery generates an automatic docked footer effect
// Window load event used just in case window height is dependant upon images
$(window).bind("load", function () {
var footerHeight = 0,
footerTop = 0,
$footer = $("#footer");
positionFooter();
function positionFooter() {
footerHeight = $footer.height();
footerTop = ($(window).scrollTop() + $(window).height() - footerHeight) + "px";
/* DEBUGGING
console.log("Document height: ", $(document.body).height());
console.log("Window height: ", $(window).height());
console.log("Window scroll: ", $(window).scrollTop());
console.log("Footer height: ", footerHeight);
console.log("Footer top: ", footerTop);
*/
if (($(document.body).height() + footerHeight) < $(window).height()) {
$footer.css({
position: "absolute"
}).stop().animate({
top: footerTop
});
} else {
$footer.css({
position: "static"
});
}
}
$(window)
.scroll(positionFooter)
.resize(positionFooter);
});
10. Prevent multiple form submissions
$(document).ready(function() {
$('form').submit(function() {
if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
jQuery.data(this, "disabledOnSubmit", { submited: true });
$('input[type=submit], input[type=button]', this).each(function() {
$(this).attr("disabled", "disabled");
});
return true;
}
else
{
return false;
}
});
});
11. Image scaling, etc
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
0
12, the mouse sliding in and out
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
1
13. Make contour columns
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
2
14. Image pre-loading
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
15. Get the parameters passed in URL
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
4
16. Disable the enter key for form submission
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
5
17. Make the entire DIV clickable
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
6
18. Open the link in a new window (target= "blank")
var $element = $('#gbtags');
var $nodes = $element.contents();
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) {
$(this).wrap('');
}
});
7
You can learn from previous articles on this site and summarize the useful jQuery code snippets for later use.