JQuery

Attribute

Vérifier si l’attribut de l’élément HTML existe

var attr = $(this).attr('name');
 
// For some browsers, `attr` is undefined; for others, `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
  // Element has this attribute
}

Bouton submit

Désactiver le double clic sur le submit

$(button).click(function () {
  $(button, this).val('Please Wait...').attr('disabled', 'disabled');
}) ;

Bouton Voir plus

jQuery load first 3 elements, click “load more” to display next 5 elements - JSFiddle

Dupliquer un élément

$(".add-row").click(function() { 
  var number = $(".row-duplicate:last").attr('number');
  var temp = $(".row-duplicate:last").clone()
  $(temp).attr('number',++number).insertAfter(".row-duplicate:last");
});

Élément this

// Use this in the parent element
$('.parent').find(this).addClass('state-active');
// Use enfant is this element
$(this).find('.enfant').addClass('state-active');

Formulaire : Récupérer le bouton enclenché

$('form[name=contact]').submit(function (e) {
  e.preventDefault();
  var button = $(this).find("input[type=submit]:focus") ;                               
});

Image : Preview before and after upload

How to preview a image before and after upload?

Impression

newwin = window.open('','printwin','left=100,top=100,width=400,height=400');
newwin.document.write('<HTML>\n<HEAD>\n');
newwin.document.write('<TITLE>Print Page</TITLE>\n');
newwin.document.write('<script>\n');
newwin.document.write('function chkstate(){\n');
newwin.document.write('if(document.readyState=="complete"){\n');
newwin.document.write('window.close()\n');
newwin.document.write('}\n');
newwin.document.write('else{\n');
newwin.document.write('setTimeout("chkstate()",2000)\n');
newwin.document.write('}\n');
newwin.document.write('}\n');
newwin.document.write('function print_win(){\n');
newwin.document.write('window.print();\n');
newwin.document.write('chkstate();\n');
newwin.document.write('}\n');
newwin.document.write('<\/script>\n');
newwin.document.write('</HEAD>\n');
newwin.document.write('<BODY onload="print_win()">\n');
newwin.document.write(data);
newwin.document.write('</BODY>\n');
newwin.document.write('</HTML>\n');
newwin.document.close();

Impression écran

Désactiver la touche Impression écran

$(document).ready(function() {
  $(window).keyup(function(e) {
    if (e.keyCode == 44) {
      $("body").hide();
    }
  }); 
});

Masonry Grid

Full-screen responsive gallery using CSS and Masonry

Medias queries

Lancer des scripts en fonction du responsive : La méthode matchMedia ou les Media Queries pour JavaScript

Mobile

if (/Android|BlackBerry|iPhone|iPad|iPod|webOS/i.test(navigator.userAgent) === false) {}

Mouvement de la souris

var global = this;
document.onmousemove = function () {
  var task;
  return function (event) {
    if (task) clearTimeout(task);
    if ((event = event || global.event)) {
      task = setTimeout(mousestop, 500);
    }
  };
 
  function mousestop() {
    /* Do stuff when the mouse stops moving. This function will be called as soon as the mouse
     * stops moving within the viewport for 500ms or more. Note that movement outside the
     * viewport (in other applications, across the desktop, or amongst the browser chrome) will
     * not be considered; it cannot be tracked.
     */
     console.log('stop');
  }
}();

Navigateur

// Internet Explorer
navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0

// Firefox
navigator.userAgent.indexOf("Firefox") != -1

Orientation de l’écran

previousOrientation = window.orientation;	
	
var checkOrientation = function(){
if (window.orientation !== previousOrientation) {
  previousOrientation = window.orientation;

  if (windowWidth >= 320 && windowWidth <= 767) {
    /* Orientation : Paysage */
    if (window.orientation != 0) { /* TODO */ } else { /* TODO */ }
  } else if (windowWidth >= 768 && windowWidth <= 1280) {
    /* Device : Tablette */
    /* Orientation : Portrait */
    if (window.orientation == 0) { /* TODO */ } else { /* TODO */ }
  }
}

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

Paramètres d’une URL

function urlParam(sParam) {
  var sPageURL = decodeURIComponent(window.location.search.substring(1)),
    sURLVariables = sPageURL.split('&'),
    sParameterName,
    i;
 
  for (i = 0; i < sURLVariables.length; i++) {
    sParameterName = sURLVariables[i].split('=');
 
    if (sParameterName[0] === sParam) {
      return sParameterName[1] === undefined ? true : sParameterName[1];
    }
  }
}

Ou

(location.search.split('idsearch=')[1] || '').split('&')[0]

Random string

var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
 
for( var i = 0 ; i < 10 ; i++ ) {
  text += possible.charAt(Math.floor(Math.random() * possible.length));
}

RGB to Hexa

How to Convert RGB Colors to Hexadecimal

Script

Appeler un script dans un script JS, synchrone.

$.ajax({ url:"script.js", dataType: "script", async: false });
$.getScript("/path/script.js", function() { myFunction(myParam); }) ;
$("<link/>", { rel: "stylesheet", type: "text/css", href: "assets/css/style.css" }).appendTo("head");

Scroll horizontal

Scroll Page Horizontally With Mouse Wheel

Trier un tableau par colonne

$('table th').click(function() {
  var table = $(this).parents('table').eq(0);
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
  this.asc = !this.asc;

  if (!this.asc) { rows = rows.reverse(); }
  for (var i = 0; i < rows.length; i++) {
    table.append(rows[i]); 
  }
});
 
function comparer(index) {
  return function(a, b) {
    var valA = getCellValue(a, index), valB = getCellValue(b, index);
    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
  }
}

function getCellValue(row, index) { 
  return $(row).children('td').eq(index).html(); 
}

Trier un tableau par search field

<input type="text" id="sortAction" onkeyup="sortTableAction()">
function sortTableAction() {
  var filter = $("#sortAction").val().toUpperCase();
  
  $("#table-action-commerciale tr td").each(function() {
    if ($(this)) {
      if($(this).html().toUpperCase().index(filter) > -1) {
        $(this).parent().css('display','');
      }
      else {
        $(this).parent().css('display','none');
      }
    }
  });
}

Variable

// Si data n’est pas null
var data = data || 'null';