Results for jquery : 27

2 - dropdown - exemples
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>
<div class="dropup">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>


avec headers
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu3">
  ...
  <li role="presentation" class="dropdown-header">Dropdown header</li>
  ...
</ul>



avec séparateurs
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuDivider">
  ...
  <li role="presentation" class="divider"></li>
  ...
</ul>

			
3 - button dropdown menus
<!-- Single button -->
<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
    Action <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li class="divider"></li>
    <li><a href="#">Separated link</a></li>
  </ul>
</div>



<!-- Split button -->
<div class="btn-group">
  <button type="button" class="btn btn-danger">Action</button>
  <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
    <span class="caret"></span>
    <span class="sr-only">Toggle Dropdown</span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li class="divider"></li>
    <li><a href="#">Separated link</a></li>
  </ul>
</div>
			
4 - Menu en accordeon
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingTwo">
      <h4 class="panel-title">
        <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingThree">
      <h4 class="panel-title">
        <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
    </div>
    <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
			
5 - Collapse un div via un bouton
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
  Link with href
</a>
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
  Button with data-target
</button>
<div class="collapse" id="collapseExample">
  <div class="well">
    ...
  </div>
</div>
			
6 - checkbox et radio sous forme de boutons
<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox" autocomplete="off"> Checkbox 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox" autocomplete="off"> Checkbox 3
  </label>
</div>

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>
			
7 - popover
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on left
</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on top
</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="bottom" data-content="Vivamus
sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on bottom
</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="right" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on right
</button>
			
8 - tooltip
<a href="#" data-toggle="tooltip" title="" data-original-title="Default tooltip">you probably</a>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left">Tooltip on left</button>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Tooltip on top</button>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom">Tooltip on bottom</button>

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right">Tooltip on right</button>
			
9 - alert modale
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

// pour détecter la fermeture de la boite
$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

On peut alors recupérer les données saisies 
autres events: show.bs.modal shown.bs.modal hidden.bs.modal loaded.bs.modal
			
10 - Se passer de Jquery
Évènements

// jQuery
$(document).ready(function() {
  // code
})

// Vanilla
document.addEventListener('DOMContentLoaded', function() {
  // code
})
// jQuery
$('a').click(function() {
  // code…
})

// Vanilla
[].forEach.call(document.querySelectorAll('a'), function(el) {
  el.addEventListener('click', function() {
    // code…
  })
})
Sélecteurs

// jQuery
var divs = $('div')

// Vanilla
var divs = document.querySelectorAll('div')
// jQuery
var newDiv = $('<div/>')

// Vanilla
var newDiv = document.createElement('div')
Attributs

// jQuery
$('img').filter(':first').attr('alt', 'My image')

// Vanilla
document.querySelector('img').setAttribute('alt', 'My image')
Classes

// jQuery
newDiv.addClass('foo')

// Vanilla
newDiv.classList.add('foo')
// jQuery
newDiv.toggleClass('foo')

// Vanilla
newDiv.classList.toggle('foo')
Manipulation

// jQuery
$('body').append($('<p/>'))

// Vanilla
document.body.appendChild(document.createElement('p'))
// jQuery
var clonedElement = $('#about').clone()

// Vanilla
var clonedElement = document.getElementById('about').cloneNode(true)
// jQuery
$('#wrap').empty()

// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)
Navigation

// jQuery
var parent = $('#about').parent()

// Vanilla
var parent = document.getElementById('about').parentNode
// jQuery
if($('#wrap').is(':empty'))

// Vanilla
if(!document.getElementById('wrap').hasChildNodes())
// jQuery
var nextElement = $('#wrap').next()

// Vanilla
var nextElement = document.getElementById('wrap').nextSibling
AJAX

GET

// jQuery
$.get('//example.com', function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.open('GET', url)
httpRequest.send()
POST

// jQuery
$.post('//example.com', { username: username }, function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))
JSONP

// jQuery
$.getJSON('//openexchangerates.org/latest.json?callback=?', function (data) {
  // code
})

// Vanilla
function success(data) {
  // code
}
var scr = document.createElement('script')
scr.src = '//openexchangerates.org/latest.json?callback=formatCurrency'
document.body.appendChild(scr)
			
11 - Slideshow minimaliste
/* CSS */
<style>
.fadein .carrousel .links{clear:both;width:100%;txtr}
.fadein { position:relative; width:100%; height:300px; } 
.fadein .carrousel { position:absolute; left:0; top:0; }

</style>
/* HTML */
<div class="fadein">
	<div class="carrousel car1">
		
		<div class="content">
			<h1>Titre du premier</h1>
			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
			tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupihref="" datat non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

		</div>
		<div class="links">
			<em>1</em>
			<a href="" data="car2">2</a>
			<a href="" data="car3">3</a>
		</div>
	</div>
	<div class="carrousel car2">
		<div class="content">
			Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupit non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
		</div>
		<div class="links">
			
			<a href="" data="car1">1</a>
			<em>2</em>
			<a href="" data="car3">3</a>
		</div>
	</div>

	<div class="carrousel car3">
		<div class="content">
		</div>		
		<div class="links">			
			<a href="" data="car1">2</a>			
			<a href="" data="car2">3</a>
			<em>3</em>
		</div>
	</div>

</div>

/* JS/JQuery */
<script>
	$('.fadein .carrousel:gt(0)').hide();compteur=0;
	function slideshow(){
		z=setInterval(
			function(){
				compteur++;
				if (compteur==4){montre=1;cache=3;compteur=1;}
				else if (compteur>1){montre=compteur;cache=compteur-1;}
				else if (compteur==1){montre=1;cache=3;}
				
			  	$('.fadein > .car'+cache).fadeOut(500)
				.parent().find('.car'+montre).fadeIn(500)
				.end();
			}
		,5000);
		return z;
	}
	slide=slideshow();

        // si on survole, pause
	$('.fadein').hover(function(ev){
    	clearInterval(slide);
	}, function(ev){
		  slide = slideshow();
		}
	);
 
        // clic sur un lien pour changer de diapo
        $('.links a').click(function(){
        	car=$(this).attr('data');
        	$('.fadein > .carrousel').fadeOut(500)
		.parent().find('.car'+car).fadeIn(500)
		.end();
		compteur=car;
    	        return false;
        });

</script>
			
12 - calcul de tailles pour galerie aux tailles d'image optimisée
viewport_width = $(window).width()
ideal_height = parseInt($(window).height() / 2)
summed_width = photos.reduce ((sum, p) -> sum += p.get('aspect_ratio') * ideal_height), 0
rows = Math.round(summed_width / viewport_width)
 
if rows < 1
  # (2a) Fallback to just standard size 
  photos.each (photo) -> photo.view.resize parseInt(ideal_height * photo.get('aspect_ratio')), ideal_height
else
  # (2b) Distribute photos over rows using the aspect ratio as weight
  weights = photos.map (p) -> parseInt(p.get('aspect_ratio') * 100)
  partition = linear_partition(weights, rows)

  # (3) Iterate through partition
  index = 0
  row_buffer = new Backbone.Collection
  _.each partition, (row) ->
    row_buffer.reset()
    _.each row, -> row_buffer.add(photos.at(index++))
    summed_ratios = row_buffer.reduce ((sum, p) -> sum += p.get('aspect_ratio')), 0
    row_buffer.each (photo) -> photo.view.resize parseInt(viewport_width / summed_ratios * photo.get('aspect_ratio')), parseInt(viewport_width / summed_ratios)

			
13 - Charger du contenu dans un select dynamiquement
$(function(){
  $("select#ctlJob").change(function(){
    $.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#ctlPerson").html(options);
    })
  })
})
			
15 - Parser du Json
function parseJson(){
	//Start by calling the json object, I will be using a 
        //file from my own site for the tutorial 
	//Then we declare a callback function to process the data
	$.getJSON('hcj.json',getPosts);
 
	//The process function, I am going to get the title, 
        //url and excerpt for 5 latest posts
	function getPosts(data){
 
		//Start a for loop with a limit of 5 
		for(var i = 0; i < 5; i++){
			//Build a template string of 
                        //the post title, url and excerpt
			var strPost = '<h2>' 
				      + data.posts[i].title
				      + '</h2>'
				      + '<p>'
				      + data.posts[i].excerpt
				      + '</p>'
				      + '<a href="'
				      + data.posts[i].url
				      + '" title="Read '
				      + data.posts[i].title
				      + '">Read ></a>';
 
			//Append the body with the string
			$('body').append(strPost);
 
		}
	}
 
}
 
//Fire off the function in your document ready
$(document).ready(function(){
	parseJson();				   
});
			
18 - Charger du contenu onscroll
var loading = false;
$(window).scroll(function(){
	if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
		if(loading == false){
			loading = true;
			$('#loadingbar').css("display","block");
			$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
				$('body').append(loaded);
				$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
				$('#loadingbar').css("display","none");
				loading = false;
			});
		}
	}
});

$(document).ready(function() {
	$('#loaded_max').val(50);
});
			
19 - Redimensionner les images automatiquement
$(window).bind("load", function() {
	// IMAGE RESIZE
	$('#product_cat_list img').each(function() {
		var maxWidth = 120;
		var maxHeight = 120;
		var ratio = 0;
		var width = $(this).width();
		var height = $(this).height();
	
		if(width > maxWidth){
			ratio = maxWidth / width;
			$(this).css("width", maxWidth);
			$(this).css("height", height * ratio);
			height = height * ratio;
		}
		var width = $(this).width();
		var height = $(this).height();
		if(height > maxHeight){
			ratio = maxHeight / height;
			$(this).css("height", maxHeight);
			$(this).css("width", width * ratio);
			width = width * ratio;
		}
	});
	//$("#contentpage img").show();
	// IMAGE RESIZE
});
			
22 - capturer un évènement sur un objet créé après chargement
$(document).on("click", "a", function(){ 
// capturer un evenement sur un objet cree apres chargement
    
 }); 
			
23 - Carrousel minimaliste
<div class="fadein">
 <img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg">
 <img src="http://farm3.static.flickr.com/2597/4121218611_040cd7b3f2.jpg">
 <img src="http://farm3.static.flickr.com/2531/4121218751_ac8bf49d5d.jpg">
</div>
In thinking about the CSS, I decided to just lock all the images into the same place using absolute positioning.

.fadein { position:relative; width:500px; height:332px; }
.fadein img { position:absolute; left:0; top:0; }
jQuery Slideshow
Now to think about the slideshow. First, I knew that I'd want to hide all the images except the first one.

$('.fadein img:gt(0)').hide();
You have to remember that the image index starts at 0. That means that we want all images after the first one to be hidden.

Next, I need a setInterval to iterate through the images every few seconds.

setInterval(function(){ },3000);
From here, I started writing this out piece by piece to get what I wanted. I needed the first image to fade out.

$('.fadein :first-child').fadeOut()
After that, I need the next image to fade in.

.next('img').fadeIn()
Then I needed to take the first image and throw it onto the end of the stack.

.end().appendTo('.fadein')
The end() resets jQuery's internal reference back to the original selection. That way, it's the :first-child that I'm appending to the end of the .fadein element and not the next('img').

That's it?
Well, yes. That's it.

$(function(){
	$('.fadein img:gt(0)').hide();
	setInterval(function(){
	 $('.fadein :first-child').fadeOut()
		 .next('img').fadeIn()
		 .end().appendTo('.fadein');}, 
	 3000);
});
			
24 - Détecter le navigateur

$(document).ready( function() { 
   if ($.browser.webkit == true) { var browser = "webkit"; } 
   else if ($.browser.mozilla == true) { var browser = "mozilla"; } 
   else if ($.browser.msie == true) { var browser = "msie"; }
   else if ($.browser.opera == true) { var browser = "opera"; }
   else { var browser = "inconnu"; }
   var version = $.browser.version;
   alert("Navigateur: "+browser+" - Version : "+version);
});
			
25 - Passer à l'input suivant en appuyant sur entrée
$('input').keydown(function(event){
            if (event.which==13){
                $(this).next('input').focus();};
});
			
26 - placeholder avec fallback jquery
<script type="text/javascript">jQuery(function($){
    var isPlaceholderSupported = function () { 
        var o = document.createElement('input'); 
        return "placeholder" in o; 
    };
    if (!isPlaceholderSupported()) {
        var togglePlaceholderText = function (el) {    
            var color = '#999';
            var v = $.trim(el.val());
            var p = el.attr('placeholder'); 
            if (v == '') { 
                el.val(p); 
                el.css({'color':color}); 
            } else if (v == p) {
                el.val(''); 
                el.css({'color':''});
            } 
        };
        $('input[placeholder]')
            .each(function(){togglePlaceholderText($(this));})
            .click(function(){togglePlaceholderText($(this));})
            .blur(function(){togglePlaceholderText($(this));})
            .closest('form').submit(function(){$(this).find('input[placeholder]').each(function(){togglePlaceholderText($(this));})});
    }

    //alert pour montrer que cela fonctionne
    $('form').submit(function(){
        alert($(this).serialize());
    });
});
</script>
			
27 - Tester l'appui sur une touche
$(document).keypress(function(e){
        switch(e.which){
        // ENTER
        case 13:
        alert('enter pressed');
        break;

        (...)

        }
    });
});