Skip to content

Latest commit

 

History

History
426 lines (322 loc) · 7.14 KB

L2_07_JQuery_Snippets.md

File metadata and controls

426 lines (322 loc) · 7.14 KB
marp title paginate author
false
Fondamenti
true
mauro

bg

Mauro Bogliaccino

JQuery code snippets utili

JQuery: gestire gli effetti


bg

VALIDARE i moduli

Molto utili per guidare l'utente nella compilazione e segnalare degli errori.


bg

Implementiamo il form

<li>
<label>Nome</label>
<input type="text" id="nome" name="nome" class="obbligatorio" />
</li>
<li>
<label>Indirizzo</label>
<input type="text" id="indirizzo" name="indirizzo "/>
</li>
<li>
<label>Email</label>
<input type="text" id="email" name="email" class="obbligatorio" />
</li>
<li>
<input type="button" id="invia" name="invia" value="invia" onclick="controlla()" />
</li>

bg

FORM VALIDATION: LOGICA

function controlla(){
    $(".obbligatorio ").each( function(){
    if( ($(this).val()=="") ){
        errore=true;
        $(this).prev().addClass('rosso');
    }
    else{ 
        $(this).prev().removeClass('rosso'); 
    }})

    if(errore==true) { 
        alert("Il form contiene errore/i, si prega di correggere."); 
    }
    else {
        alert("Complimenti! Non ci sono errori!"); 
    }
}
</script>

bg

Bottone torna su

$('a.top').click(function(){
$(document.body).animate({scrollTop : 0},800);
return false;
});
<a class="top" href="#">Back to top</a>

bg

Controlla see img sono caricate

$('img').load(function() {
console.log('image load successful');
});

bg

Ripara immagini mancanti

$('img').error(function(){
$(this).attr('src', 'img/broken.png');
});

bg

Toggle class su hover

$('.btn').hover(function(){
$(this).addClass('hover');
}, function(){
$(this).removeClass('hover');
}
);

bg

Disabilitare input fields

$('input[type="submit"]').attr("disabled", true);

$('input[type="submit"]').removeAttr("disabled");

bg

ferma il caricamento links

$('a.no-link').click(function(e){
e.preventDefault();
});

bg

Toggle fade/slide

// Fade
$( .btn" ).click(function() {
$( .element" ).fadeToggle("slow");
});

// Toggle
$( .btn" ).click(function() {
$( .element" ).slideToggle("slow");
});

bg

Semplice accordion

// Close all Panels
$('#accordion').find('.content').hide();
// Accordion
$('#accordion').find('.accordion-header').click(function(){
var next = $(this).next();
next.slideToggle('fast');
$('.content').not(next).slideUp('fast');
return false;
});

bg

Fai 2 div con la stessa altezza

$('.div').css('min-height', $('.main-div').height());

bg

ul zebra style

$('li:odd').css('background', '#E8E8E8');

bg

Invia data asando il metodo GET

jQuery( document ).ready(function() {
	jQuery.get( "mypage.php", { name: "John", time: "2pm" } )
		.done(function( data ) {
		alert( "Data Loaded: " + data );
	});
});

bg

Invia data usando il metodo POST

jQuery("button").click(function(){
    jQuery.post("page.php", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

bg

Recevi testo da una webpage

<ol id="new-projects"></ol>
 
<script>
jQuery( document ).ready(function() {
	jQuery( "#new-projects" ).load( "/resources/load.html #projects li" );
});
</script>

bg

Prendi tutti i valori da un form e inviali ad una pagina web

jQuery( document ).ready(function() {
	jQuery( "#submit" ).click(function() {
		 jQuery.post( "https://yoursite.com/yourpage.php", jQuery('#form').serialize())
			.done(function( data ) {
			alert(data);
		}); 
		return false;
	});
});

bg

Ricevi JSON data

jQuery.getJSON( "http://yoursite.com/test.json", function( data ) {
        alert(data);
});
jQuery.getJSON( "http://yoursite.com/test.json", function( data ) {
        var obj = JSON.parse(data);
        jQuery( "#container" ).html(obj.name + ", " + obj.age);
});

bg

Come mostrare tutti i sotto elementi in jQuery

 $("#link1").click(function(){
    $("#p").show();
    $("#p").children().show();
});
$("#link2").click(function(){
   $("#small1").hide(); 
});
$("#link3").click(function(){
   $("#middle2").hide(); 
});

bg

jQuery.unique()

 var divs = $( "div" ).get();
 
divs = divs.concat( $( ".test1" ).get() );
$( "div:eq(1)" ).text( "This is cool " + divs.length + " element." );
 
divs = jQuery.unique( divs );
$( "div:eq(2)" ).text( "jQuery is very fun to" + divs.length + " learn.." )
  .css( "color", "blue" );

// Ordinare un array di elementi del DOM, rimuovendoi duplicati. Non funziona con stringhe o numeri

bg

jQuery Dimensions

 $(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "
";
        txt += "Height of div: " + $("#div1").height() + "
";
        txt += "Outer width of div (margin included): " + $("#div1").outerWidth(true) + "
";
        txt += "Outer height of div (margin included): " + $("#div1").outerHeight(true);
        $("#div1").html(txt);
    });
});

bg

jQuery.each()

 $(document).ready(function(){
    $("button").click(function(){
        $("li").each(function(){
            alert($(this).text())
        });
    });
});

bg

Fade out page

 $(document).ready(function(){

/*! Fades in whole page on load */
$('body').css('display', 'none');
$('body').fadeIn(500);

});

bg

Submit form

 var tId;
$('input[type="checkbox"]').change(function(){
    clearTimeout(tId);
    tId=setTimeout(function(){
      $('#top_header_form').submit();
    },650);
});

bg

jQuery getJSON() Method

 $("button").click(function(){
    $.getJSON("demo_json.js", function(result){
        $.each(result, function(i, field){
            $("div").append(field + " ");
        });
    });
});

bg

Aggiungere icone ai link con jQuery

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

bg

Assegnare la classe "active" alla navbar con jQuery

 $(function() {
      $( 'ul.nav li' ).on( 'click', function() {
            $( this ).parent().find( 'li.active' ).removeClass( 'active' );
            $( this ).addClass( 'active' );
      });
});