jQuery snippets

Много других сниппетов для jQuery вы найдёте в статьях сайта. Для быстрого поиска перейдите на страницу "Карта сайта".

Запрет перехода по ссылкеПолучить текст ссылкиПереход по ссылке при клике на divСделать кнопку неактивной (см. Запрет перехода по ссылке)Ссылки в новой вкладкеАвтоматическое обнаружение ссылки на документ и задание классаСдвиг ссылкиСобытие EnterSelectЗначение по умолчанию в selectЗапрет правого кликаИзменение в зависимости от разрешенияВыделить каждый второй элементПоказать блок, если отметить чекбоксОператоры (более короткая запись)Выравнивание блока по центру экранаПроверка задан ли классПроверка существования элемента на страницеАдаптивная вёрстка с помощью jQueryОб анимацииМигание текстаЗацикливание анимацииЗапрет выделения текстаОтключить скроллинг страницы под модальным окномОпределение capsLockОбрабатывать только первый клик при многократном нажатииАккордеонПодгрузка скриптов. Метод getScriptВвод только цифрыAdjust Youtube embeds to correct ratioПростое переключение стилейСоздание элемента динамическиСоздание оверлея и удаление его при кликеВставить элемент между других элементовDelete all inline styling in a page with jQueryСообщение в верхней части страницыПлавный скролл от якоряВремя загрузки страницыТолько цифры в input textСкролл наверхДобавить-удалить класс на hoverПоказать значение массива с помощью циклаСкрыть div за 5 секунд (setTimeout)ЗебраУдалить класс после задержкиПередача значений value в массивеОтследить прокрутку до низа страницыОтследить прокруткуПрокрутка до 64pxОтследить прокрутку страницы равную высоте экранаОтметить первую радиокнопкуЦентрирование элемента, полученного с помощью запроса AjaxИнтерактивный заголовокЦепочкаОтметить все чекбоксыЧекбоксВыбрать все, отменить все, получить номер выбранныхЗначениеРадиокнопки1Радиокнопки2Простое слайдшоуВыбор цвета фонаВыпадающий блок с задержкойRedirectПерезагрузка каждые 5 секундПростой плагинТолько 2 чекбокса!Удаление похожих видео в конце просмотра ролика YouTubeIPЗапрет выделения текстаЗакрыть окно через 2000мсwmode=transparent для iframeПоказ div при выборе в списке и нажатии кнопкиdiv будет скрыт, если ввести в поле 0Вывод датыПоказать значение selectОбновить страницуЗащита EmailПростой счётчикПростой HTML5 аудиоплеер с плейлистомHTML5 аудиоплеер - переход на начало и повторениеHTML5 аудиоплеер - счётчикПростой слайдерПриветствие в зависимости от времени сутокПереключение класса по третьему кликуПолучить href и altАльтернативное подключение библиотеки jQueryAudio-Video playerОбновление конкретного блока на страницеdata-toggleУбрать из меню titleDynamic Copyright YearДействие по нажати Esc (Escape)Select - ячейки таблицыПрокрутка наверх Scroll topПредотвратить повтор анимации

Запрет перехода по ссылке

$(function() {
  $('a').parent().click(function(e){
    e.preventDefault();
    alert($(this).attr('href')); 
  });
});

Через jQuery (в случае, когда не используется return false;) это можно сделать удалив атрибут href:

$('a').removeAttr('href');

Или так (добавить return false; программно):

$("a").click(function() { return false; });

Или так:

$("a.btn").click(function(e) {
     e.preventDefault();
     // код
});

Или так:

$("a.btn").click(function() {
     // код
     return false;
});

Или так (все ссылки, имеющие "#" вместо адреса):

$('a[href="#"]').click(function(event){ 
		event.preventDefault(); 
	});

Javascript:

<li><a href="javascript: void(0);">Мой словарь</a></li>

Или так:

<li><a href="javascript:;">Мой словарь</a></li>

Или так:

<a href="#" onclick="return false">Мой словарь</a>

Получить текст ссылки

jQuery:

$('a').click(function(e) {
    var a = $(this).text();
	alert(a)
	// или
	$('#div').val(a);
        // или
	$('#div').text(a);
	return false
});

HTML:

<a href='#'>текст</a>

Переход по ссылке при клике на div

jQuery:

$(document).ready(function(){
     $(".div").click(function(){
          window.location=$(this).find("a").attr("href"); 
          return false;
     });
});

HTML:

<div class="div">
    content
    <a href="http://google.com">link</a>
</div>

Сделать кнопку неактивной (см. Запрет перехода по ссылке)

$('a.btn').click(function(e) {
    e.preventDefault();
});

Ссылки в новой вкладке

$(document).ready(function(){
	$("a[href^='http://']").attr("target","_blank");
});

Автоматическое обнаружение ссылки на документ и задание класса

$('a[href]').each(function() {
   if((C = $(this).attr('href').match(/[.](doc|xls|pdf)$/))) {
       $(this).addClass(C[1]);
   }
});

Сдвиг ссылки

$(function(){
   $("a.show_form").hover(function() {
      $(this).stop().animate({paddingLeft : "20px"},200);
          },function() {
             $(this).stop().animate({paddingLeft : "0px"},200);
   });
	
});

Событие Enter

$("#input").keypress(function(e) {
	if(e.keyCode == 13) {
		// ...
            return false;
	}
});

Select

jQuery:

$(document).ready( function() {
	 $('select').change( function () {
		 // Создаём переменную и получаем значение селекта
		 var sl = $('#sel :selected').val();
		 // если выбрано значение "зелёный" (value = "green")	
		 if (sl == 'green')
		 {
			 // Указываем свойства
			 $('#block').css({'background-color':'green','width':'300px'});
		 }
		 else 
		 // иначе... или так: else if (sl == 'blue')
		 {
			 $('#block').css({'background-color':'blue','width':'200px'});
		 }
		 });	 
	 });

HTML:

<select id="sel">
  <option value = "green">Зелёный</option>
  <option value = "blue">Голубой</option>
</select>

Значение по умолчанию в select

jQuery:

$(function(){
    $('select[value]').each(function(){
        $(this).val(this.getAttribute("value"));
    });

HTML:

//The Markup Looks Like This
<select name="category" id="category" value="PHP">  //NOTICE value attribute!!!
      <option value="ARTICLE">ARTICLE</option>
      <option value="PHP">PHP</option>  //THIS IS THE DEFAULT OPTION
      <option value="MySql">MYSQL</option>
      <option value="jQuery">jQuery</option>
      <option value="CSS(3)">CSS(3)</option>
</select>

Запрет правого клика

<!-- jQuery: отключить контекстное меню -->
$(document).bind("contextmenu", function(e){
    e.preventDefault();
})
// или так:
$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});
// или так (для изображений):
$(document).ready(function() {
     $('img').bind("contextmenu", function(e){ return false; })
});

Изменение в зависимости от разрешения

$(window).resize(function() { 
    if($(window).width() < 1000 )
        $('#div').css('margin-top','-60px');
});

Выделить каждый второй элемент

jQuery:

$(document).ready(function () {
    $('ul.example li:nth-child(2n)').addClass('red').show();
});

CSS:

.red {
    color: red;
}

HTML:

<ul class="example">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Показать блок, если отметить чекбокс

jQuery:

$(document).ready(function() {    
    $('#div').css({display: 'none'}); 
    $('#checkbox').change(function () {        
        if ($(this).is(':checked')) {
            $('#div').fadeIn();
            return;
        } 
        $('#div').fadeOut(); 
    }); 
})

HTML:

<input type="checkbox" id="checkbox" /> 
<div id="div"></div>

Или по имени:

if($('input[name="test"]').is(":checked"))
{
  // my other code
 }

Можно с помощью .prop:

if ($(this).prop('checked')) {

Операторы (более короткая запись)

jQuery:

$(document).ready(function(){ 
	var n = $("#example div").length;
	if (n < 2) {
		$("body").css("background", "green");
	} 
	else {
		$("body").css("background", "orange");
	}
});
// Так короче:
$(document).ready(function() {
	var n = $("#example div").length;
	$("body").css("background", (n < 2) ? "green" : "orange");
});

HTML:

<div id="example">
	<div></div>
	<div></div>
</div>

Выравнивание блока по центру экрана

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
 
//Use the above function as:
$(element).center();

Проверка задан ли класс

if ( $("#myDiv").hasClass("red") ) {
alert("У элемента задан класс red");
}
// Несколько классов
if ( $("#myDiv").hasClass("red") && $("#myDiv").hasClass("green") ) {
alert("У элемента заданы оба класса: red и green");
}
// Хотя бы один
if ( $("#myDiv").hasClass("red") || $("#myDiv").hasClass("green") ) {
alert("У элемента задан какой-то из классов: red или green");
}

Проверка существования элемента на странице

if($("#findID").length>0) {
  // exists
}
// или так:
if($("#findID").length) {
  // exists
}
// или так:
if($('#findID')[0]) {
 // exists
}
// или так:
var obj = $('#myId');
if (obj.length) {
    // объект был найден
}
else {
    // объект пустой
}
// или так:
var el = $('selector').html();
if (el == '') alert('Тэг пустой');
else alert('В тэге что-то есть!');
создадим пользовательскую функцию exists() 
// Один раз объявляем функцию, потом используем так, как в примере
jQuery.fn.exists = function() {
   return $(this).length;
}
// Пример использования:
if($("#findID").exists()) {
   // exists
}
Можно и так:
jQuery.exists = function(selector) {
   return ($(selector).length > 0);
}
 
// Пример использования:
if ($.exists(selector)) {
  // exists
}
// Пример 1. Удостоверимся, что блок с идентификатором test является пустым.
var emptyElement = $('#test').is(':empty');
if (emptyElement == true) {
    alert('Элемент пустой!');
}
// Пример 2. Попробуем выделить все пустые элементы на веб-странице зеленой рамочкой толщиной под три пиксела.
$('*').each(function() {
    if ($(this).text() == "") {
        $(this).css('border', 'solid 3px green');
    }
});

Адаптивная вёрстка с помощью jQuery

<script type="text/javascript">
  $(document).ready(function() {
    var w = $(window).width(); // Получаем ширину окна
    if (w <= 480) { // Если ширина окна меньше, либо равна 600
      $("#left").html($("#left").html() + $("#right").html()); // Копируем содержимое правой колонки в левую
      $("#right").remove(); // Удаляем правую колонку
    }
  });
</script>
// ещё
$(document).ready(function($) {
  
    /* getting viewport width */
    var responsive_viewport = $(window).width();
    
    /* if is below 481px */
    if (responsive_viewport < 481) {
    
    } /* end smallest screen */
    
    /* if is larger than 481px */
    if (responsive_viewport > 481) {
        
    } /* end larger than 481px */
    
    /* if is above or equal to 768px */
    if (responsive_viewport >= 768) {
        
    }
    
    /* off the bat large screen actions */
    if (responsive_viewport > 1030) {
        
    }
    
});

Об анимации

// пункты меню увеличиваются до 100 px в высоту при наведении мышкой:
$('#myList li').mouseover(function() {  
    $(this).animate({"height": 100}, "slow");  
});
// второй эффект сразу после первого:
$('#myBox').mouseover(function() {  
    $(this).animate({ "width": 200 }, "slow");  
    $(this).animate({"height": 200}, "slow");  
});  
// эффекты протекают одновременно:
$('#myBox').mouseover(function() {  
    $(this).animate({ "width": 200, "height": 200 }, "slow");  
});

Мигание текста

<script type="text/javascript" >
	function blink(selector){
		$(selector).fadeOut('slow', function(){
			$(this).fadeIn('slow', function(){
				blink(this);
			});
		});
	}
	
	$(document).ready(function(){
		blink('.blink');	
	});	
</script>

Зацикливание анимации

jQuery:

$(document).ready(function(){
function function_name() {    //создаем функцию с именем function_name
$("#demo").animate({       //добавляем парочку анимаций
"marginLeft" : "+=500px"}, 3000)
.animate({
"marginLeft" : "-=500px"}, 3000, function_name); // по завершению последней анимации вызываем нашу функцию в качестве callback
};
function_name();  //запускаем нашу функцию
//Второй пример
function function_name2() {
$("#demo2").hide(1000).show(1000, function_name2)};
function_name2();
});

HTML:

<div id="demo">Я буду болтаться туда-сюда бесконечно! Убейте меня кто нибудь!</div>
<div id="demo2">Я буду болтаться туда-сюда бесконечно! Убейте меня кто нибудь!</div>

Запрет выделения текста

 Spoiler conten$(document).ready(function(e) {
	$("body").on("mousedown", "#wrapper", function (e) {
		e.preventDefault();
		});    
});

На CSS:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

Отключить скроллинг страницы под модальным окном

Вариант первый
В момент открытия окна:

$('body').css('overflow','hidden');

Или так:

$('body').css('overflow-y','hidden');

В момент закрытия модального окна:

$('body').css('overflow','auto');

При этом скроллбар скрывается и весь контент сдвигается. Чтобы этого избежать, можно сделать так:
HTML:

<body>
  <div id="main">
      <!-- здесь содержание HTML страницы -->
  </div>
</body>

В момент открытия окна:

$('#main').css('width', $('#main').css('width'));
$('body').css('overflow', 'hidden');

В момент закрытия модального окна:

$('body').css('overflow', 'auto');
$('#main').css('width', 'auto');

Определение capsLock

$('#password').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
        alert('caps is on');
    }
});

Обрабатывать только первый клик при многократном нажатии

jQuery:

var flag = false;
$('button').click(function(){
    if (flag) return false;
    flag = true;
    $('div').animate({left: '+=100px'}, function(){flag = false;});                                                 
});

CSS:

div {
    position: absolute;
    width: 50px;
    height: 50px;
    top: 50px;
    left: 0;
    background: red;
}

HTML:

<div></div>
<button>move</button>

Аккордеон

jQuery (вариант 1):

$(document).ready(function(){
	$('.spoiler-head').click(function(){
    	$('.spoiler-body').hide('500');
		$(this).next('.spoiler-body').toggle('500');
	});
});

jQuery (вариант 2):

$(document).ready(function(){
    var ac;
    $('.spoiler-head').click(function(){
        ac = $(this).next('.spoiler-body');
        $('.spoiler-body').not(ac).slideUp(500);
        ac.slideToggle(500);
    })
});

CSS:

ul {
	list-style-type: none;
}
.spoiler-body {
	display: none;
}

HTML:

<ul>
  <li>
    <div class="spoiler-head">Заголовок 1</div>
    <div class="spoiler-body">Текст 1</div>
  </li>
  <li>
    <div class="spoiler-head">Заголовок 2</div>
    <div class="spoiler-body">Текст 2</div>
  </li>
  <li>
    <div class="spoiler-head">Заголовок 3</div>
    <div class="spoiler-body">Текст 3</div>
  </li>
</ul>

Подгрузка скриптов. Метод getScript

// Предположим, на сервере у нас определен следующий простенький скрипт redStyle.js:
$('body').css('background-color', 'red');
// Скрипт просто окрашивает страницу в красный цвет. Теперь на странице определим его подгрузку, например, по нажатию кнопки:
<button>Загрузить</button>
<script type="text/javascript">
$(function(){
    $('button').click(function(){
        $.getScript('redStyle.js');
    });
});
</script>

Ввод только цифры

$(document).ready(function() {
	$("#txtboxToFilter").keydown(function(event) {
		// Allow only backspace and delete
		if ( event.keyCode == 46 || event.keyCode == 8 ) {
			// let it happen, don't do anything
		}
		else {
			// Ensure that it is a number and stop the keypress
			if (event.keyCode < 48 || event.keyCode > 57 ) {
				event.preventDefault();	
			}	
		}
	});
});

Adjust Youtube embeds to correct ratio

/* Remind to delete all width & height inline references on embed code */
//var ratio = 3/4;
var ratio = 9/16;
$(".youtube > iframe").height($(".youtube > iframe").width() * ratio);

Простое переключение стилей

$(document).ready(function(){
	$('#styleSwitch .button').bind('click', function(){
		$('body').removeClass();//remove all the other classes
		$('#styleSwitch .button').removeClass('selected');
		$(this).addClass('selected');
		switch(this.id){
			case 'style1':
				$('body').addClass('style1');
				break;
			case 'style2':
				$('body').addClass('style2');
				break;
			case 'style3':
				$('body').addClass('style3');
				break;
		}
		return false;
	});
});

Создание элемента динамически

var newDiv = $('<div></div>');
newDiv.attr("id","myNewDiv").appendTo("body");

Создание оверлея и удаление его при клике

$('<div id="overlay"></div>')
    .css({
        position    : 'fixed',
        top         : 0,
        left        : 0,
        right       : 0,
        bottom      : 0,
        opacity     : 0.6,
        background  : 'black',
        display     : 'none'
    })
    .appendTo('body')
    .fadeIn('normal')
    .click(function () {
        $(this).fadeOut('normal', function () {
            $(this).remove();
        })
    });

Вставить элемент между других элементов

$("p:not(:last-of-type)").after("<br />");

Delete all inline styling in a page with jQuery

$("*[style]").attr("style", "");
// или так:
$( "*[style]" ).removeAttr( "style" );

Сообщение в верхней части страницы

function messageAjax (msg) {
    if (jQuery("body").find("#infoBox").length == 0) {
		jQuery("body").prepend("<div id=\"infoBox\" style=\"height: 20px;background-color:#ffffff;width:100%;display:none;text-align:center;border-bottom:#2BBAE4 1px solid;\"></div>");
	} // END IF
	
	jQuery("body").find("#infoBox").text(msg).slideDown().delay(3000).slideUp();
}
messageAjax('I m on top of everything');

Плавный скролл от якоря

$(document).ready(function() {
    $("a.topLink").click(function() {
		$("html, body").animate({
			scrollTop: $($(this).attr("href")).offset().top + "px"
		}, {
			duration: 500,
			easing: "swing"
		});
		return false;
	});
});

с отступом

$('a.scrollid').click(function () {
      $root.animate({
          scrollTop: $( $.attr(this, 'href') ).offset().top - 5
      }, 700, 'easeInOutExpo');
   
      return false;
  });

Время загрузки страницы

//calculate the time before calling the function in window.onload
var beforeload = (new Date()).getTime();
function getPageLoadTime(){
        //calculate the current time in afterload
        var afterload = (new Date()).getTime();
        // now use the beforeload and afterload to calculate the seconds
        seconds = (afterload-beforeload) / 1000;
        // Place the seconds in the innerHTML to show the results
        $('#load_time').text('Page load time ::  ' + seconds + ' sec(s).');
}
window.onload = getPageLoadTime;

Только цифры в input text

$(".prodcounts").keypress(function(e){
     if((e.which!=8) && (e.which!=0) && (e.which<48 || e.which>57)) {
	return false;
     }
});

Скролл наверх

$(document).ready(function() {
    $('img#top').click(function() {
	$('html, body').animate({scrollTop: 0}, 300);
    });
});

Добавить-удалить класс на hover

$('.onhover').hover(  
  function(){ $(this).addClass('hover_style_class') },  
  function(){ $(this).removeClass('hover_style_class') }  
)

Показать значение массива с помощью цикла

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Sorting</title>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js?ver=3.2.1'></script>
    <script type="text/javascript">
        $('document').ready(function () {
            var arr = [52, 97, 3, 62, 10, 63, 64, 1, 9, 3, 4];
            for (i = 0; i < arr.length; i++) {
                $('p#test' + i).html(arr[i]);
            }
        });
    
    </script>
</head>
<body>
<h1>This is a sorting example</h1>
<p id="test0">test</p>
<p id="test1">test</p>
<p id="test2">test</p>
<p id="test3">test</p>
<p id="test4">test</p>
<p id="test5">test</p>
<p id="test6">test</p>
<p id="test7">test</p>
<p id="test8">test</p>
<p id="test9">test</p>
<p id="test10">test</p>
<div><input type="button" value="sort" id="sortButton" /></div>
</body>
</html>

Скрыть div за 5 секунд (setTimeout)

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>hide div com setInterval</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script>
$(document).ready(function() {
	function sumir_floater() {
		var div = $("#floater");
		div.fadeIn();
		div.queue(function() {
			setTimeout(function() {
				div.dequeue();
			}, 5000);
		});
	div.fadeOut("fast");
	}
sumir_floater();
});
</script>
</head>
<body>
<div id="floater">
  <p>Image or Text here</p>
</div>
</body>
</html>

Зебра

// make zebra stripes
var zebraodd = "#364146";
var zebraeven = "#102227";
$("table.zebra tr:odd, ul.zebra li:odd").css("background-color", zebraodd);
$("table.zebra tr:even, ul.zebra li:even").css("background-color", zebraeven);

Удалить класс после задержки

var link = $('#link');
link.addClass('current');
setTimeout(function() {
	link.removeClass('current');
}, 3000);

Передача значений value в массиве

$(function () {
	$('input:radio, input:checkbox').val(['chb_2', 'chb_3', 'rb_4']);
});
// радио кнопка с атрибутом value="rb_4" и чекбоксы с атрибутами value="chb_2", value="chb_3" будут отмечены

Отследить прокрутку до низа страницы

$(window).scroll(function() 
{
     if  ($(window).scrollTop() == $(document).height() - $(window).height()) 
     {
          //Пользователь долистал до низа страницы
     }
});

Отследить прокрутку

$(window).on("scroll", function() {
    if ($(window).scrollTop() > 50) $('.header').addClass('fixed');
          else $('.header').removeClass('fixed');
    });
body {
	margin:0;
}
.header {
	height:200px;
	background:yellow;
}
.fixed {
	height:100px;
	width:100%;
	position:fixed;
	background:green;
}
.content {
	height:10000px;
	background:blue;
}
<div class="header"></div>
<div class="content"></div>

Прокрутка до 64px

$('.toAnchor').on('click', function () {
  $a = $($(this).attr('href'));
  $('html,body').animate({ scrollTop: $a.offset().top - 64}, 500);
  return false;
});
#menu {
    background: red;
    width: 100%;
    height: 64px;
    line-height: 64px;
    position: fixed;
    text-align: center;
}
<div id="menu">меню</div>
<div style="height: 100px;"></div>
<a href="#anchor" class="toAnchor">ссылка для перехода</a>
<div style="height: 500px;"></div>
<a id="anchor">якорь</a>
<div style="height: 500px;"></div>

Отследить прокрутку страницы равную высоте экрана

$(window).scroll(function () {
    if ($(this).scrollTop() > $(window).height()) {
        // действия по достижении нужной точки
    } else {
        // действия по возврату
    }
});
// или так:
// Если высота окна + высота прокрутки больше или равны высоте всего документа не доходя 200 px
        if($(window).scrollTop() + $(window).height() >= $(document).height()- 200) {
...
}
// Пример:
$(document).ready(function(){
	$(window).scroll(function() {
		if ($(this).scrollTop() > $(window).height()) {
			$('body').css('background-color','red');
			} else {
				$('body').css('background-color','green');
			}
	});
});

Отметить первую радиокнопку

$("input:radio[name=gender]:first").click();

Центрирование элемента, полученного с помощью запроса Ajax

Предположим, что мы имеем абсолютно позиционированный родительский элемент, и запрос Ajax, который подгружает элемент с неизвестными заранее размерами внутри позиционированного элемента. Как мы можем центрировать этот элемент?

(function( $ ) {
	$.fn.center = function ( parent ) {
    	this.css( "position", "absolute" );
 
 
		var position = parent.position();
    
		this.css( "top", Math.max( 0, ( ( parent.height() - this.outerHeight() ) / 2 ) + position.top ) + "px" );
     
		this.css( "left", Math.max( 0, (( parent.width() - this.outerWidth() ) / 2 ) + position.left ) + "px" );
    
		return this;
	};
})( jQuery );
// Пример использования:
$.get( "ajax.php", function( html ) {
	var $parent = $( "#test" );
	$( html ).
	appendTo( $parent ).center( $parent );
});

Интерактивный заголовок

(function( $ ) {
	$(function() {
		var pageURL = location.href;
		var $pageHeading = $( "h1" );
		$pageHeading.wrapInner( "<a href='" + pageURL + "'></a>" );
	});
})( jQuery );

Цепочка

$("#Div").show("slow", function () {
    $("#Div2").show("slow");
});

Пример

$(".top").animate({opacity: 0.4}, 1500 ).animate({opacity: 1.0}, 1500 );

Пример

jQuery:

var duration = 500;
$('div')
.animate({opacity: 1}, duration)
.queue(function() {
    $(this).text('Погнали!').dequeue();
})
.animate({width: '+=100'}, duration)
.animate({left: '+=200'}, duration)
.animate({backgroundColor: '#060'}, duration)
.animate({top: '+=200'}, duration)
.animate({backgroundColor: '#900'}, duration)
.animate({height: '+=100'}, duration)
.animate({left: '-=200'}, duration)
.animate({top: '-=200'}, duration)
.animate({backgroundColor: '#036'}, duration)
.queue(function() {
    $(this).text('Приехали!').dequeue();
})
.animate({fontSize: '2.5em'}, duration);
// И еще сколько угодно действий

CSS:

div {
    position: absolute;
    width: 100px;
    height: 100px;
    background: #999;
    color: #fff;
    opacity: 0;
}

HTML:

<div></div>

Отметить все чекбоксы

$(function() {
    $('#checkAll').on('change', function() {
        $('input:checkbox').prop('checked', this.checked);
    });   
});
<input type="checkbox" id="checkAll" />
<label for="chkAll">(un)check all</label>
<div>
    <input type="checkbox" id="chk1" />
    <label for="chk1">checkBox 1</label>
    <input type="checkbox" id="chk2" />
    <label for="chk2">checkBox 2</label>
    <input type="checkbox" id="chk3" />
    <label for="chk3">checkBox 3</label>
</div>

Чекбокс

$(this).change(function(){ 
  if($(this).attr("checked")){ 
  // делаем что-то, когда чекбокс включен 
  }else{ 
  // делаем что-то другое, когда чекбокс выключен 
  } 
});

Выбрать все, отменить все, получить номер выбранных

$(document).ready(function(){
    // выбрать все чекбоксы
    $('#checkbox_cancel').click(function(){
        $('input#checkbox').each(function(){
            $(this).attr('checked', false);
        });
    });
     
    // отменить все чекбоксы
    $('#checkbox_check').click(function(){
        $('input#checkbox').each(function(){
            $(this).attr('checked', true);
        });
    });
     
    // получить номера выбранных чекбоксов
    $('#checkbox_get').click(function(){
        var num = 1;
        $('input#checkbox').each(function(){
            if($(this).prop("checked")){
                alert(num);
            }
            num ++;
        });
    });
});
<div id="work_div">
    <input type="checkbox" id="checkbox" checked="checked" />
    <input type="checkbox" id="checkbox"/>
    <input type="checkbox" id="checkbox"  checked="checked"/>
    <input type="checkbox" id="checkbox"/>
    <input type="checkbox" id="checkbox"/>
    <br/>
    <input type="button" id="checkbox_cancel" value="Снять все чекбоксы" /><br/>
    <input type="button" id="checkbox_check" value="Выбрать все чекбоксы" /><br/>
    <input type="button" id="checkbox_get" value="Получить номера выбранных" />
</div>

Значение

$("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     
    alert(value);
});
// или так:
if ($("#checkBoxId").is(':checked') == true) {
    alert("Checked");
}
else {
    alert("Unchecked");
}

Радиокнопки1

$('input:radio').click(function(){
$('#1').text($(this).attr('price1'));
            $('#2').text($(this).attr('price2'));
        });
<form name="form" method="post" action="">
      <fieldset style="width: 50%;">
        <input type="radio" name="opt1" value="1" price1="100" class="1" />Option 1<br />
        <input type="radio" name="opt1" value="2" price1="200" class="1"/>Option 2<br />
        <input type="radio" name="opt1" value="3" price1="300" class="1"/>Option 3<br />
      </fieldset>
      <fieldset style="width: 50%;">
        <input type="radio" name="opt2" value="1" price2="10" class="2"/>Option 1<br />
        <input type="radio" name="opt2" value="2" price2="20" class="2"/>Option 2<br />
        <input type="radio" name="opt2" value="3" price2="30" class="2"/>Option 3<br />
      </fieldset>
    </form>
    Totals:
    <div id="1"></div>
    <div id="2"></div>

Радиокнопки2

$(document).ready(function() {
	$('#myForm input').on('change', function() {
   alert($('input[name=radioName]:checked', '#myForm').val()); 
});
});
// или так:
$('input[name="radioName"]').on('change', function() {
  var radioValue = $('input[name="radioName"]:checked').val();        
  alert(radioValue); 
});
<form id="myForm">
<input type="radio" name="radioName" value="1" /> 1 <br />
<input type="radio" name="radioName" value="2" /> 2 <br />
<input type="radio" name="radioName" value="3" /> 3 <br />
</form>

Простое слайдшоу

$(function() {
   // Скрываем 1-й div
   $("#slideshow > div:gt(0)").hide(); 
   // Функция setInterval для смены блока каждые 3000 мс
   setInterval(function() {
      // Первый блок плавно исчезает за 1000 мс 
      $('#slideshow > div:first') .fadeOut(1000) .next() .fadeIn(1000) // Появляется
      .end() .appendTo('#slideshow'); }
   , 3000); 
   }
);
<div id="#slideshow">
  <div style="display: block;"> Текст текст текст. </div>
  <div style="display: none;"> <img src="1.jpg"> </div>
  <div style="display: none;"> <img src="2.jpg"> </div>
</div>
#slideshow {
	margin: 80px auto;
	position: relative;
	width: 240px;
	height: 240px;
	padding: 10px;
	box-shadow: 0 0 20px rgba(0,0,0,0.4);
}
#slideshow > div {
	position: absolute;
	top: 10px;
	left: 10px;
	right: 10px;
	bottom: 10px;
}

Выбор цвета фона

<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 if ($.cookie("bg_color")!='') $("body").css("background-color",$.cookie("bg_color"));
 $("#bg_form").change(function(){
    $("body").css("background-color",$("#bg_form :selected").val());
    $.cookie("bg_color",$("#bg_form :selected").val(), {expires: 1});
 });
});
</script>

Параметр expires определяет время жизни куки в днях
Скачать

Выпадающий блок с задержкой

<!doctype html>
<html>
<head>
<meta charset="windows-1251">
<title>Документ без названия</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
setTimeout(function () {
        $('#block').animate({
            top: 530
        }, 2000);
});
});
</script>
<style>
#block {
	width: 50px;
	height: 50px;
	background-color: #D90D10;
	position: fixed;
	margin-left: 50px;
	margin-top: -500px;
}
</style>
</head>
<body>
<div id="block"></div>
</body>
</html>

Redirect

$(document).ready(function () {
	setTimeout(function(){
		document.location.href = 'https://www.google.ru/';
		},5000);
});

Перезагрузка каждые 5 секунд

$(document).ready(function () {
	setTimeout(function(){
		document.location.href = document.location;
		},5000);
});

Простой плагин

(function($){				   
	jQuery.fn.extend({
		//Options is added within the brackets after function
		// This informs the plugin that options will be used
		redBorder: function(options) {
			
			//Defaults options are set
			var defaults = {  
				border: "3px solid red"  
			};  
			var options = $.extend(defaults, options);  
			
			return this.each(function() {   
			
				jQuery(this).css("border", options.border);
			
			});
		}
	});
})(jQuery);

Вызов:

$(document).ready(function(){ 	
	$("p").redBorder({border: "3px dotted green"});	
});

Только 2 чекбокса!

jQuery:

$(document).ready(function () {
    $("input[name='tech']").change(function () {
        var maxAllowed = 2;
        var cnt = $("input[name='tech']:checked").length;
        if (cnt > maxAllowed) {
            $(this).prop("checked", "");
            alert('You can select maximum ' + maxAllowed + ' technologies!!');
        }
    });
});

HTML:

<b>Select Maximum 2 technologies:</b>
<br/>
<br/>
<input type="checkbox" name="tech" value="jQuery" /> jQuery
<br/>
<input type="checkbox" name="tech" value="JavaScript" /> JavaScript
<br/>
<input type="checkbox" name="tech" value="Prototype" /> Prototype
<br/>
<input type="checkbox" name="tech" value="Dojo" /> Dojo
<br/>
<input type="checkbox" name="tech" value="Mootools" /> Mootools
<br/>

Удаление похожих видео в конце просмотра ролика YouTube

jQuery:

$(document).ready(function () {
    $('iframe[src*="youtube.com"]').each(function () {
        var sVideoURL = $(this).attr('src');
        if (sVideoURL.indexOf('rel=0') == -1) {
            $(this).attr('src', sVideoURL + '?rel=0');
        }
    });
});

HTML:

<iframe width="420" height="315" src="https://www.youtube.com/embed/zP0avMuysEQ" frameborder="0" allowfullscreen></iframe>

IP

$(document).ready(function () {
    $.get('http://jsonip.com', function (res) {
        $('p').html('IP Address is: ' + res.ip);
    });
});

Запрет выделения текста

jQuery.fn.extend({
disableTextSelection : function() {
this.each(function() {
this.onselectstart = function() { return false; };
this.unselectable = "on";
jQuery(this).css('-moz-user-select', 'none');
});
},
enableTextSelection : function() {
this.each(function() {
this.onselectstart = function() {};
this.unselectable = "off";
jQuery(this).css('-moz-user-select', 'auto');
});
}
});

Вызов:

$("body *, body").disableTextSelection();

Закрыть окно через 2000мс

setTimeout(function() {
	window.close();
}, 2000);

wmode=transparent для iframe

/* Set wmode=transparent for iframes to show it under the menus, lightboxes etc. */
jQuery(function ($) {
    "use strict";
    $("iframe[src]").each(function () {
        var iframe = $(this);
        var src = iframe.attr("src");
        if (src == "") {
            return;
        }
        if (src.lastIndexOf("?") !== -1) {
            src += "&wmode=transparent";
        } else {
            src += "?wmode=transparent";
        }
        iframe.attr("src", src);
    });
});

Показ div при выборе в списке и нажатии кнопки

jQuery:

$(document).ready(function() {
    $("#div1").hide();
    $("#div2").hide();
    $("#div3").hide(); 
    $("#div4").hide();
    $("#div5").hide();
   $("#pick_go").click(function() {
        var openId = $("#pick_select").val();
        $("#div1").hide();
        $("#div2").hide();
        $("#div3").hide(); 
        $("#div4").hide();
        $("#div5").hide();
        $("#div" + openId).fadeIn();
    });
});

HTML:

<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
<select id="pick_select" style="height:40px; width:300px;">
  <option value="">Kies een Instelling</option>
  <option value="1">Wachtwoord veranderen</option>
  <option value="2">Veiligheidsvraag veranderen</option>
  <option value="3">PIN veranderen</option>
  <option value="4">Inlog Geschiedenis inzien</option>
  <option value="5">Account ter veiligheid blokkeren</option>
</select>
<input type="submit" value="Openen" id="pick_go"style="height:40px; width:90px;" name="vp_picker_submit" class="submit" />

div будет скрыт, если ввести в поле 0

jQuery:

$(document).ready(function() {
    $('#userInput').on('input',function(){
    if( $(this).val() == 0 )
        $('#myDiv').hide();
    else
        $('#myDiv').show();
});
});

HTML:

<div id="myDiv"> This Div will be hidden when you enter zero. </div>
<input type="text" id="userInput"/>

Вывод даты

$.date = function(){
    return new Date().toLocaleString();
};
alert($.date());

Результат: вывод даты

Показать значение select

jQuery:

$(document).ready(function() {
   $('#mydropdownid').on("change",function(){
    var selectedValue=$('#mydropdownid').val();
    var selectedText=$('#mydropdownid option:selected').text();
    alert(selectedValue + " : " + selectedText);
    
});
});

HTML:

<select id="mydropdownid">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

Обновить страницу

$('.link a').click(function(){
        location.reload();
    });

Через секунду:

$('.link a').click(function(){
    setTimeout(function() {window.location.reload();}, 1000);
});

Защита Email

/* Simple spam protection for email addresses using jQuery.
 * Well, the protection isn’t jQuery-based, but you get the idea.
 * This snippet allows you to slightly ‘obfuscate’ email addresses to make it harder for spambots to harvest them, while still offering a readable address to your visitors.
 * E.g.
 * <a href="mailto:foo(at)example(dot)com">foo at example dot com</a>
 * →
 * <a href="mailto:foo@example.com">foo@example.com</a>
 */
$(function() {
 $('a[href^="mailto:"]').each(function() {
  this.href = this.href.replace('(at)', '@').replace(/\(dot\)/g, '.');
  // Remove this line if you don't want to set the email address as link text:
  this.innerHTML = this.href.replace('mailto:', '');
 });
});

Простой счётчик

jQuery:

var counter = 0;
setInterval('timer()', 1000);
function timer() {
	counter++;
	$("#counter").text(counter);
	}

HTML:

<div id="counter">0</div>

Простой HTML5 аудиоплеер с плейлистом

CSS:

#playlist,audio{background:#666;width:400px;padding:20px;}
.active a{color:#5DB0E6;text-decoration:none;}
li a{color:#eeeedd;background:#333;padding:5px;display:block;}
li a:hover{text-decoration:none;}

jQuery:

var audio;
var playlist;
var tracks;
var current;
init();
function init(){
    current = 0;
    audio = $('audio');
    playlist = $('#playlist');
    tracks = playlist.find('li a');
    len = tracks.length - 1;
    audio[0].volume = .10;
    playlist.find('a').click(function(e){
        e.preventDefault();
        link = $(this);
        current = link.parent().index();
        run(link, audio[0]);
    });
    audio[0].addEventListener('ended',function(e){
        current++;
        if(current == len){
            current = 0;
            link = playlist.find('a')[0];
        }else{
            link = playlist.find('a')[current];    
        }
        run($(link),audio[0]);
    });
}
function run(link, player){
        player.src = link.attr('href');
        par = link.parent();
        par.addClass('active').siblings().removeClass('active');
        audio[0].load();
        audio[0].play();
}

HTML:

<audio id="audio" preload="auto" tabindex="0" controls type="audio/mpeg">
        <source type="audio/mp3" src="http://www.archive.org/download/bolero_69/Bolero.mp3">
        Sorry, your browser does not support HTML5 audio.
    </audio>
    <ul id="playlist">
        <li class="active"><a href="http://www.archive.org/download/bolero_69/Bolero.mp3">Ravel Bolero</a></li>
        <li><a href="http://www.archive.org/download/MoonlightSonata_755/Beethoven-MoonlightSonata.mp3">Moonlight Sonata - Beethoven</a></li>
        <li><a href="http://www.archive.org/download/CanonInD_261/CanoninD.mp3">Canon in D Pachabel</a></li>
        <li><a href="http://www.archive.org/download/PatrikbkarlChamberSymph/PatrikbkarlChamberSymph_vbr_mp3.zip">patrikbkarl chamber symph</a></li>
    </ul>

HTML5 аудиоплеер - переход на начало и повторение

jQuery:

$(document).ready(function(){
$("#audio-player")[0].play();//To play
      $("#audio-player")[0].pause(); //To pause
//For Ringtone will repeat
      $("#audio-player")[0].addEventListener('ended', function () {
                    this.currentTime = 0;
                    //this.play();
                }, false);
});

HTML:

<audio id="audio-player" src="musica.mp3" controls ></audio>

HTML5 аудиоплеер - счётчик

//Вариант первый
$(переменная audio).on("timeupdate", function() {
	var time = this.currentTime;
	var m = Math.floor(time / 60);
	var s = Math.floor(time - (m * 60));
	if(s < 10) s = '0'+s;
	if(m < 10) m = '0'+m;
	$('#current').text( m +':'+ s);
});
//Вариант второй
$(переменная audio).on("timeupdate", function() {
	var time = this.currentTime;
	curM = Math.floor(c/60);
	curS = Math.round(c - curM*60);
	$('#current').text(curM + ':' + curS);
});
//Общая длительность
$(переменная audio).on("playing", function () {
	dur = this.duration;
	durM = Math.floor(dur/60) + ':' + Math.round((dur - Math.floor(dur/60))/10);
    $('#duration').text(durM);
});

Простой слайдер

jQuery:

$(document).ready(function() {
	var images = ["1.jpg", "2.jpg", "3.jpg"];
	var currentimage =0;
	$("#img").attr("src", images[currentimage]); // обращаемчя к массиву и берём нулевой элемент 1.jpg
	$("#back").click(function() {
		//если текущая картинка не является первой, то
        if (currentimage != 0) {
			//уменьшаем значение переменной currentimage на одно
			currentimage--;
			$("#img").attr("src", images[currentimage]); 
		}
    });
	$("#forward").click(function() {
		//если текущая картинка не является последней, то
        if (currentimage != images.length - 1) {
			//увеличиваем значение переменной currentimage на одно
			currentimage++;
			$("#img").attr("src", images[currentimage]); 
		}
    });
});

HTML:

<div class="wrap">
<img id="img" alt="">
<div>
  <button id="back">Назад</button>
  <button id="forward">Вперёд</button>
</div>
</div>

Приветствие в зависимости от времени суток

$(document).ready(function() {
var d = new Date();
var hours = d.getHours();
if (hours < 12 && hours >= 6) {
		$("#block").text("Доброе утро!");
	}
	else if (hours >= 12 && hours < 18) {
		$("#block").text("Добрый день!");
	}
	else if (hours >= 18 && hours <= 23) {
		$("#block").text("Добрый вечер!");
	}
	else if (hours >= 0 && hours < 4) {
		$("#block").text("Доброй ночи!");
	}
	else if (hours >= 4 && hours <= 6) {
		$("#block").text("Доброе утро!");
	}
});

Переключение класса по третьему клику

$(this).toggleClass("highlight", count++ % 3 == 0);

Получить href и alt

Для одного изображения:

var text_alt = $("img").attr("alt");
	$("div").text(text_alt);

href - аналогично
Для нескольких изображений:
HTML:

<div id="album-artwork">
<ul>
   <li><a href="javascript:void(0);"><img src="images/ajax-loader.gif" alt="ajax-loader" /></a></li>
   <li><a href="javascript:void(0);"><img src="images/close.png" alt="close" /></a></li>
   <li><a href="javascript:void(0);"><img src="images/copy.png" alt="copy" /></a></li>
</ul>
</div>

jQuery:

$(document).ready(function() {
        $("#album-artwork a").click(function(e) {
            e.preventDefault();
            var src = $(this).attr("href");
            //var alt = $(this).next("img").attr("alt");
            var alt = $(this).children().attr("alt");
            //find function also do the same thing if you want to use.
            /*var alt = $(this).find("img").attr("alt");*/
            alert(src); // ok!
            console.log(src); // ok!
            alert(alt); //output: not undefined now its ok!
            console.log(alt); //output: not undefined now its ok!
        });
    });

the children() function find any children but if you want to find any specific children define the children name like this children("img") OR children("button")

Альтернативное подключение библиотеки jQuery

<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script>window.JQuery || document.write('<script src="js/jquery-3.1.1.min.js"><\/script>');</script>

Audio-Video player

Громкость

var pl = jQuery('#player').get(0);
// Громкость 50%;
pl.volume = 0.5;

Или так:

var pl = jQuery('#player')[0];
// Громкость 50%;
pl.volume = 0.5;

Или так:

$('.audio').prop("volume", 0.1);

Регулировка кнопками (в сочетании с ванильным Js; конечно, событие click можно передать и jQuery)

<button class="btn-radio" onclick="$('#player')[0].volume+=0.1">+</button>
<button class="btn-radio" onclick="$('#player')[0].volume-=0.1">-</button>

Mute/Unmute

$("video").prop('muted', true);
  $("#mute-video").click( function (){
    if( $("video").prop('muted') ) {
          $("video").prop('muted', false);
    } else {
      $("video").prop('muted', true);
    }
  });

Play/Pause

jQuery( document ).ready(function($) {
    $('.myHTMLvideo').click(function() {
        this.paused ? this.play() : this.pause();
    });
});

Или:

$('video').click(function(){
    this[this.paused ? 'play' : 'pause']();
});

Приостановка нескольких видео

$("video").each(function(){
    $(this).get(0).pause();
});

Или (scrollTop):

$(window).scroll(function() {
    if($(window).scrollTop() > 0)
        document.querySelector('#video').pause();
    else
        document.querySelector('#video').play();
});

Или:

$('.player_audio').click(function() {
  if (this.paused == false) {
      this.pause();
      alert('music paused');
  } else {
      this.play();
      alert('music playing');
  }
});

Или в сочетании с JavaScript:

$(document).ready(function() {
    var playing = false;
    $('a#button').click(function() {
        $(this).toggleClass("down");
        if (playing == false) {
            document.getElementById('player').play();
            playing = true;
            $(this).text("stop sound");
        } else {
            document.getElementById('player').pause();
            playing = false;
            $(this).text("restart sound");
        }
    });
});

Переключатель - две кнопки:

// Play
$('.play').trigger("play");
// Pause
$('.play').trigger("pause");
// Если нужно получить доступ:
$('.play').prop("paused");

You can access element its methods and properties by jQuery.get e.g. $('.play').get(0) or $('.play)[0] Then you can use the play() or plause() methods and the paused property to check if the video is paused. $('.play').get(0).paused is boolean - true if it is paused, false if isn't.
It may be old but you can access the paused attributes with $('.play').prop("paused");
Also helpful if you need to set play time to 0 : $(".audioDemo").prop("currentTime",0);
В сочетании с JavaScript:

<script type="text/javascript">
    $('#mtoogle').toggle(
        function () {
            document.getElementById('playTune').pause();
        },
        function () {
            document.getElementById('playTune').play();
        }
    );
</script>

Или:

$("#button").click(function() {
        var bool = $("#player").prop("muted");
        $("#player").prop("muted",!bool);
        if (bool) {
            $("#player").prop("currentTime",0);
        }
});

Простой переключатель

jQuery:

$(function() {
    $('.trigger').on('click', function() {
      $('audio').prop('src', $(this).data('src'));
    });
  });

HTML:

<audio preload="auto" src="#" autoplay="true" controls></audio>
<a class="trigger"#" data-src="audio/song4.mp1">Song1</a>
<a class="trigger"#" data-src="audio/song4.mp2">Song2</a>
<a class="trigger"#" data-src="audio/song4.mp3">Song3</a>

Обновление конкретного блока на странице

setInterval(function() {
$("#refresh").load(location.href+" #refresh>*","");
}, 10000); // milliseconds to wait

Каждые 10 секунд будет автоматически обновляться блок #refresh.

data-toggle

HTML:

<a data-toggle="n1" href="1" id="button" class="c1">Ответить 1</a>
<a data-toggle="n2" href="2" id="button" class="c2">Ответить 2</a>

jQuery:

$('a').click(function(){
    alert($(this).attr('data-toggle'))
    return false
})

Ещё пример

HTML:

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">

jQuery:

$("button").on("click", function(){
  $($(this).attr("data-target")).modal("show");
});

или:

$("button").on("click", function(){
  $($(this).data("target")).modal("show");
});

Убрать из меню title

jQuery(document).ready(function(){
	jQuery("#header li").find('a').removeAttr('title');
});

Убрать titlle при наведении на миниатюры в галерее GT3 Photo & Video Gallery - Lite (плагин Вордпресс):

$(".gt3pg_img_wrap").removeAttr('title');

Dynamic Copyright Year

HTML:

Copyright © 2018 - <span id="spanYear"></span>

jQuery:

$('#spanYear').html(new Date().getFullYear());

Действие по нажати Esc (Escape)

$(document).keyup(function(e){
		if (e.key === "Escape"){
			$(".hint-popup").hide(0);
			$(".hint-fade").remove();
		}
	});

Select - показать ячейки таблицы с определённым классом

jQuery:

$("#sel").change(function() {
  selected = $(this).val();
  if (selected != 0) {
    number = selected.substr(3);
    $("tr").hide();
    $("tr[class='my" + number + "']").show();
  } else {
    $("tr").show();
  }
});

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel">
  <option value="0">Select</option>
  <option value = "cat1">Category1</option>
  <option value = "cat2">Category2</option>
</select>
    <table>
    <tr class="my1">
        <td>Value 1</td>
        <td>Value 1</td>
    </tr>
    <tr class="my2">
        <td>Value 2</td>
        <td>Value 2</td>
    </tr>
    <tr class="my1">
        <td>Value 1-1</td>
        <td>Value 1-1</td>
    </tr>
    <tr class="my2">
        <td>Value 2-2</td>
        <td>Value 2-2</td>
    </tr>
    <tr class="my1">
        <td>Value 2-1</td>
        <td>Value 2-1</td>
    </tr>
</table>

Без пункта Выбрать

jQuery:

$("#sel").change(function() {
  selected = $(this).val();
  number = selected.substr(3);
  $("tr").hide();
  $("tr[class='my" + number + "']").show();
});

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel">
  <option value = "cat1">Category1</option>
  <option value = "cat2">Category2</option>
</select>
    <table>
    <tr class="my1">
        <td>Value 1</td>
        <td>Value 1</td>
    </tr>
    <tr class="my2">
        <td>Value 2</td>
        <td>Value 2</td>
    </tr>
    <tr class="my1">
        <td>Value 1-1</td>
        <td>Value 1-1</td>
    </tr>
    <tr class="my2">
        <td>Value 2-2</td>
        <td>Value 2-2</td>
    </tr>
    <tr class="my1">
        <td>Value 2-1</td>
        <td>Value 2-1</td>
    </tr>
</table>

Подсчёт строк в таблице

Прокрутка наверх

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

просто

$(window).scrollTop(0);

или

// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });

Предотвратить повтор анимации

$("#foo").hover(function () {
	$(this).stop(1, 1).animate({
		opacity: 1
	}, 500);
}, function () {
	$(this).stop(1, 1).animate({
		opacity: 0.4
	}, 300);
});