Snippet (fragement) de code jquery

Création site internet tunisie

Des fragments de code reutisable pour vos projets :

Hover On/Off

$("a").hover( function () { // code on hover over }, function () { // code on away from hover } );

Prevent Anchor Links from Loading

$("a").on("click", function(e){ e.preventDefault(); });

Scroll to Top

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

Ajax Template

$.ajax({ type: 'POST', url: 'backend.php', data: "q="+myform.serialize(), success: function(data){ // on success use return data here }, error: function(xhr, type, exception) { // if ajax fails display error alert alert("ajax error response type "+type); } });

 

Animate Template

$('p').animate({ left: '+=90px', top: '+=150px', opacity: 0.25 }, 900, 'linear', function() { // function code on animation complete });

Toggle CSS Classes

$('nav a').toggleClass('selected');

Toggle Visibility

$("a.register").on("click", function(e){ $("#signup").fadeToggle(750, "linear"); });

Loading External Content

$("#content").load("somefile.html", function(response, status, xhr) { // error handling if(status == "error") { $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText); } });

Keystroke Events

$('input').keydown(function(e) { // variable e contains keystroke data // only accessible with .keydown() if(e.which == 11) { e.preventDefault(); } }); $('input').keyup(function(event) { // run other event codes here });

Equal Column Heights

var maxheight = 0; $("div.col").each(function(){ if($(this).height() > maxheight) { maxheight = $(this).height(); } }); $("div.col").height(maxheight);

Append New HTML

var sometext = "here is more HTML"; $("p#text1").append(sometext); // added after $("p#text1").prepend(sometext); // added before

Setting & Getting Attributes

var alink = $("a#user").attr("href"); // obtain href attribute value $("a#user").attr("href", "http://www.google.com/"); // set the href attribute to a new value $("a#user").attr({ alt: "the classiest search engine", href: "http://www.google.com/" }); // set more than one attribute to new values

Retrieve Content Values

$("p").click(function () { var htmlstring = $(this).html(); // obtain html string from paragraph $(this).text(htmlstring); // overwrite paragraph text with new string value }); var value1 = $('input#username').val(); // textfield input value var value2 = $('input:checkbox:checked').val(); // get the value from a checked checkbox var value3 = $('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons

Traversing the DOM

$("div#home").prev("div"); // find the div previous in relation to the current div $("div#home").next("ul"); // find the next ul element after the current div $("div#home").parent(); // returns the parent container element of the current div $("div#home").children("p"); // returns only the paragraphs found inside the current div

source