Developpement Informatique

mars 8, 2010

Sexy Drop Down Menu w/ jQuery & CSS

Filed under: CSS, JQuery — izaam01 @ 6:15

http://www.noupe.com/tutorial/drop-down-menu-jquery-css.html

Step1. HTML

First create an unordered list for your base top navigation. Then simply nest another unordered list for your sub navigation.

<ul>
    <li><a href="#">Home</a></li>
    <li>
        <a href="#">Tutorials</a>
        <ul>
            <li><a href="#">Sub Nav Link</a></li>
            <li><a href="#">Sub Nav Link</a></li>
        </ul>
    </li>
    <li>
        <a href="#">Resources</a>
        <ul>
            <li><a href="#">Sub Nav Link</a></li>
            <li><a href="#">Sub Nav Link</a></li>
        </ul>
    </li>
    <li><a href="#">About Us</a></li>
    <li><a href="#">Advertise</a></li>
    <li><a href="#">Submit</a></li>
    <li><a href="#">Contact Us</a></li>
</ul>

Step2. CSS

Next, it’s time to style the navigation wireframe with CSS.

ul.topnav {
	list-style: none;
	padding: 0 20px;
	margin: 0;
	float: left;
	width: 920px;
	background: #222;
	font-size: 1.2em;
	background: url(topnav_bg.gif) repeat-x;
}
ul.topnav li {
	float: left;
	margin: 0;
	padding: 0 15px 0 0;
	position: relative; /*--Declare X and Y axis base for sub navigation--*/
}
ul.topnav li a{
	padding: 10px 5px;
	color: #fff;
	display: block;
	text-decoration: none;
	float: left;
}
ul.topnav li a:hover{
	background: url(topnav_hover.gif) no-repeat center top;
}
ul.topnav li span { /*--Drop down trigger styles--*/
	width: 17px;
	height: 35px;
	float: left;
	background: url(subnav_btn.gif) no-repeat center top;
}
ul.topnav li span.subhover {background-position: center bottom; cursor: pointer;} /*--Hover effect for trigger--*/
ul.topnav li ul.subnav {
	list-style: none;
	position: absolute; /*--Important - Keeps subnav from affecting main navigation flow--*/
	left: 0; top: 35px;
	background: #333;
	margin: 0; padding: 0;
	display: none;
	float: left;
	width: 170px;
	border: 1px solid #111;
}
ul.topnav li ul.subnav li{
	margin: 0; padding: 0;
	border-top: 1px solid #252525; /*--Create bevel effect--*/
	border-bottom: 1px solid #444; /*--Create bevel effect--*/
	clear: both;
	width: 170px;
}
html ul.topnav li ul.subnav li a {
	float: left;
	width: 145px;
	background: #333 url(dropdown_linkbg.gif) no-repeat 10px center;
	padding-left: 20px;
}
html ul.topnav li ul.subnav li a:hover { /*--Hover effect for subnav links--*/
	background: #222 url(dropdown_linkbg.gif) no-repeat 10px center;
}

Step3. jQuery

For those who are new to jQuery, you can learn about it here.

The following script contains comments explaining which jQuery actions are being performed.

$(document).ready(function(){

	$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("ul.topnav li span").click(function() { //When trigger is clicked...

		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

});

*To degrade gracefully, we only show the drop down menu trigger to those who have javascript enabled.

Degrade Gracefully Demo in Sexy Drop Down Menu w/ jQuery & CSS

This is what it looks like when javascript is disabled:

Javascript Disabled=

View Demo of Sexy Drop Down Menu

Conclusion

Note: I went ahead and added the rounded corners to the demo (CSS3 – Only supported in Firefox, Safar, & Chrome). If you would like to give it a try, check out this tutorial.

Experiment and customize this to fit your needs! If you have any questions, concerns, suggestions, or comments, please do not hesitate to let me know.

Fancy Thumbnail Hover Effect w/ jQuery

Filed under: JQuery — izaam01 @ 6:03

Recently I was checking out some nice flash galleries and came across an effect that I really liked. I had a sudden urge to duplicate that similar effect but using my bread and butter (CSS and jQuery). I thought I’d share this and maybe some of you can find it useful.

Fancy Thumbnail Hover Effect w/ jQuery

View Demo

Build the Foundation – XHTML

Our markup will be fairly simple, just an unordered three columned list.

<ul>
	<li><a href="#"><img src="thumb1.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb2.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb3.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb4.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb5.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb6.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb7.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb8.jpg" alt="" /></a></li>
	<li><a href="#"><img src="thumb9.jpg" alt="" /></a></li>
</ul>

Dress it Up – CSS

Pay close attention to the positioning properties between the list item and the image. We have to make sure that the hovered image must be on top of the other images, so this part is key.

ul.thumb {
	float: left;
	list-style: none;
	margin: 0; padding: 10px;
	width: 360px;
}
ul.thumb li {
	margin: 0; padding: 5px;
	float: left;
	position: relative;  /* Set the absolute positioning base coordinate */
	width: 110px;
	height: 110px;
}
ul.thumb li img {
	width: 100px; height: 100px; /* Set the small thumbnail size */
	-ms-interpolation-mode: bicubic; /* IE Fix for Bicubic Scaling */
	border: 1px solid #ddd;
	padding: 5px;
	background: #f0f0f0;
	position: absolute;
	left: 0; top: 0;
}
ul.thumb li img.hover {
	background:url(thumb_bg.png) no-repeat center center;  /* Image used as background on hover effect
	border: none; /* Get rid of border on hover */
}

*Note – For more information about this property: -ms-interpolation-mode: bicubic, refer to Chris Coyier’s Bicubic Scaling fix for IE. For those who are using PNG files as the background, refer to my previous article, “PNG Transparency Fix in IE6“.

Bring it to Life – jQuery

Basically all we are doing is animating the thumbnail’s size, absolute positioning coordinates (vertical alignment w/ css), and padding when we hover over. During this animation, we also switch the value of the z-index, so that the selected image stays on top of the rest.

$("ul.thumb li").hover(function() {
	$(this).css({'z-index' : '10'}); /*Add a higher z-index value so this image stays on top*/ 
	$(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
		.animate({
			marginTop: '-110px', /* The next 4 lines will vertically align this image */ 
			marginLeft: '-110px',
			top: '50%',
			left: '50%',
			width: '174px', /* Set new width */
			height: '174px', /* Set new height */
			padding: '20px'
		}, 200); /* this value of "200" is the speed of how fast/slow this hover animates */

	} , function() {
	$(this).css({'z-index' : '0'}); /* Set z-index back to 0 */
	$(this).find('img').removeClass("hover").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
		.animate({
			marginTop: '0', /* Set alignment back to default */
			marginLeft: '0',
			top: '0',
			left: '0',
			width: '100px', /* Set width back to default */
			height: '100px', /* Set height back to default */
			padding: '5px'
		}, 400);
});

*Note – To learn more about Animation Queue Buildup, read “Quick Tip: Prevent Animation Queue Buildup” at www.LearnjQuery.com

Fancy Thumbnail Hover Effect w/ jQuery

View Demo

Conclusion

It may not be as smooth as the flash version, but its definitely a neat effect. If you switch up the absolute potion coordinates, you can create various ways the hover effect pops out as well. If you have any questions or comments, please don’t hesitate to let me know!

février 23, 2010

jquery validate form input if certain check boxes are checked

Filed under: JQuery — izaam01 @ 9:36

Assuming that you are using the jQuery validation plugin, you could set/clear the class of each of the controls in the required/not required sections based on the checkbox that was clicked.

$(document).ready( function() { $(‘form’).validate(); } );

function init_validation(divName)
{
$(‘div#’ + divName).find(‘input’).addClass( ‘required’ );
$(‘div#inputs’).children(‘div:not(#’ + divName + ‘)’)
.find(‘input’)
.removeClass( ‘required’ );
}
HTML:

New Account

Delete Account

New Software

JQuery Selectors

Filed under: JQuery — izaam01 @ 7:38

Changer la couleur de tous des

$(« p »).css(« color », « red »);

Changer la couleur du premier

$(« p:eq(0) »).css(« color », « red »);

Changer la couleur d’un

$(« p#first »).css(« color », « red »);

Selection les sans id
$(« span:not([@id]) »).css(« color », « red »);

Selection de tous les

contenant une balise
$(« p:has(span) »).css(« color », « red »);

Selection de tous les à l’intérieur d’un

$(« span »).parent(‘p’).css(« color », « red »);

Tous les

$(« div »).css(« border », »9px solid red »);

Finds every element (including head, body, etc).
$(« * »).css(« border », »3px solid red »);

Une balise bien precis

$(document).ready(function(){
$(« input[id][name$=’man’] »).val(« only this one »);
});

FORM
$(‘:input’)
$(‘:text’)
Using this psuedo-selector like $(‘:text’) is equivalent to $(‘*:text’) which is a very slow selector. It’s
recommended to do $(‘input:text’).

$(‘:password’)
$(‘:radio’)
$(‘:checkbox’)
$(‘:submit’)
// so it won’t submit
$(« form »).submit(function () { return false; });
$(‘:image’)
$(‘:reset’)
$(‘:button’)
$(‘:file’)
$(‘:hidden’)

Compter le nombre d’élémentsdans un formulaire
var allInputs = $(« :input »);
var formChildren = $(« form > * »);
$(« #messages »).text(« Found  » + allInputs.length +  » inputs and the form has  » +
formChildren.length +  » children. »);

***

one
two
three

Setting a form value with jQuery
You can set the form values with jQuery using the same val() function but passing it a new value instead. Using the same example forms above, you’d do this for the text input and select box:

$(‘#foo’).val(‘this is some example text’);
$(‘#bar’).val(‘3’);
OR
$(‘[name=foo]’).val(‘this is some example text’);
$(‘[name=bar]’).val(‘3’);

Using the above for a radio button will change the actual value of the radio button rather than changing the one that is selected. To change the radio button that is selected you’d do this:

$(‘input[name= »baz »]’)[0].checked = true;
[0] would set the first one checked, [1] would set the second one checked and so on

février 22, 2010

jQuery Sortable Lists With Drag Drop Handle

Filed under: JQuery — izaam01 @ 1:07

this post has been extended in the new Extending the jQuery Sortable With Ajax & MYSQL post

I’ve recently made use of a drag / drop style list that will remember the order of the list. If you use the standard jQuery sortable items, you’ll get the two following problems:

  1. You won’t be able to click on any items in the sortable list you have
  2. You’ll probably want an update of the order of the list after every change.

I did find a solution to the problem over at Scott Sauyet’s site, but I needed a little more… The following example will do both, it uses the handle and update options on the .sortable item. By adding these simple items you can produce a pretty advanced sortable list. You could even add AJAX into that update command and automatically update your database with the new values every time you change then removing the need to refresh, and that’s very web 2.0.

DEMO AND SOURCE HAVE MOVED TO THE NEW POST

I’ve ‘enhanced’ it ever so slightly by adding in some styles for the list items and handles.

First we’ll look at the CSS:

<style> 
  #test-list { list-style: none; padding: 0; margin: 0 40px; } 
  #test-list li { margin: 0 0 10px 0; background: #eaf3fa; padding: 15px; } 
  #test-list .handle { float: left; margin-right: 10px; cursor: move; } 
  #test-log { padding: 5px; border: 1px solid #ccc; } 
</style>

Then we need to include jQuery and the jQuery UI

<script type="text/javascript" src="{ latest jquery release }"></script> 
<script type="text/javascript" src="{ ui core }"></script> 
<script type="text/javascript" src="{ ui sortable }"></script> 

We then tell the document to automatically handle the list when it’s ready

<script type="text/javascript">// When the document is ready set up our sortable with it's inherant function(s) 
$(document).ready(function() { 
  $("#test-list").sortable({ 
    handle : '.handle', 
    update : function () { 
      $("input#test-log").val($('#test-list').sortable('serialize')); 
    } 
  }); 
}); 
</script>

Now to build the HTML:

<ul id="test-list"> 
    <li id="listItem_1"> 
    <img src="arrows.png" alt="move" /> 
      Item 1 with a link to <a href="http://www.google.co.uk/" rel="nofollow">Google</a> 
    </li> 
    <li id="listItem_2"> 
      <img src="arrow.png" alt="move" /> 
      Item 2 
    </li> 
    <li id="listItem_3"> 
      <img src="arrow.png" alt="move" /> 
      Item 3 
    </li> 
    <li id="listItem_4"> 
      <img src="arrow.png" alt="move" /> 
      Item 4 
      <p>Perhaps you want to add a form in here?</p> 
      <p>Text:<br /><input type="text" /></p> 
      <p>And a textarea<br /><textarea></textarea></p> 
    </li> 
</ul> 
<label for="test-log"><strong>Resultant order of list</strong></label> 
<input type="text" size="70" id="test-log" />

One important thing to remember, that might have you stumbling is that you HAVE to name the list items as such id=“item_1” that underscore and number will define the elements in the array past out to the text box.

Experiment, enjoy.

Extending the jQuery Sortable With Ajax & MYSQL

Filed under: JQuery — izaam01 @ 1:06

I’ve had a lot of response to the jQuery sortable list post I wrote a while back, and a lot of them ask how to send the results to a database. I’ve often said the best thing to do would be to update it by AJAX, but I’ve never really explained how. So here it is!

There was a bug a few people noticed with the new jQuery UI a short while ago that stopped the update callback working. That bug has since been rectified and all is kosher again. I have since updated the example to the latest jQuery and UI downloads. The examples and downloads have also been updated accordingly.

Step one: Create the page with the sortable, and the CSS

(described on my previous post) We have however altered it slightly, so here is the updated code (without any css, the css is in the sourcecode)
Include your javascript files, you’ll need jQuery and the jQuery UI files (sortable)

<script type="text/javascript" src="jquery-1.3.2.min.js"></script> 
<script type="text/javascript" src="jquery-ui-1.7.1.custom.min.js"></script> 
<link rel='stylesheet' href='styles.css' type='text/css' media='all' />

Then you’ll need to create your Javascript function. We’re going to listen for the list to be updated, then call the php page, pass it the new order by GET and update the #info div with whatever the PHP file prints out:

<script type="text/javascript"> 
// When the document is ready set up our sortable with it's inherant function(s) 
$(document).ready(function() { 
  $("#test-list").sortable({ 
    handle : '.handle', 
    update : function () { 
      var order = $('#test-list').sortable('serialize'); 
      $("#info").load("process-sortable.php?"+order); 
    } 
  }); 
}); 
</script>

Now here’s the HTML to output the list etc. etc:

<pre> 
    <div id="info">Waiting for update</div> 
</pre> 
<ul id="test-list"> 
  <li id="listItem_1"> 
    <img src="arrow.png" alt="move" width="16" height="16" /> 
    <strong>Item 1 </strong>with a link to <a href="http://www.google.co.uk/" rel="nofollow">Google</a> 
  </li> 
  <li id="listItem_2"> 
    <img src="arrow.png" alt="move" width="16" height="16" /> 
    <strong>Item 2</strong> 
  </li> 
  <li id="listItem_3"> 
    <img src="arrow.png" alt="move" width="16" height="16" /> 
    <strong>Item 3</strong> 
  </li> 
  <li id="listItem_4"> 
    <img src="arrow.png" alt="move" width="16" height="16" /> 
    <strong>Item 4</strong> 
  </li> 
</ul> 
<form action="process-sortable.php" method="post" name="sortables"> 
  <input type="hidden" name="test-log" id="test-log" /> 
</form>

Step two: Create the PHP to handle the serialized list jQuery has created

The PHP page will simply take the url it’s been handed and pick out the items from the array. You can then manipulate your database with the new values, or just format however you want. The code could look like this:

&lt;?php 
/* This is where you would inject your sql into the database 
but we're just going to format it and send it back 
*/ 
foreach ($_GET['listItem'] as $position => $item) : 
  $sql[] = "UPDATE `table` SET `position` = $position WHERE `id` = $item"; 
endforeach; 
print_r ($sql); 
?&gt;

You could then happily run each sql statement.

As always, I’d love the feedback, it’s great for improving the example etc. Enjoy!

février 21, 2010

Create Overlay Lightbox For Your Website Free With jQuery

Filed under: JQuery — izaam01 @ 5:49

http://www.2webvideo.com/video-production

Free jQuery For Overlay Dialog Box With Delayed Opening, Free HTML

If you stay in this page for some time and watch the following paragraph you’ll find that the portion inside the dotted boundary turns opaque with a reddish background color, and at the same time a dialog box opens up in the middle.

Example of Overlay Dialog Box

This is an example of jQuery overlay dialog box with delayed opening. The delay is set at 7 seconds which can be altered easily. The dialog box opens atop a red overlay background, all of which can be changed in the code that appears at the bottom. You can also set the dialog box to open or not to open by clicking anywhere on the webpage.

To see the overlay effect again, simply refresh this page.

Note: The above is done with iframe tag. To see how this works in an entire page, click here.]

The dialog box urges you to subscribe for 2WebVideo’s newsletter by giving your email ID in the form provided therein. If you do not want to subscribe you can hit the close button and the dialog box closes.

When using this technique many websites do not provide the close button thereby rather forcibly making the visitors to part with their email ID for subscription. This is so because except one, there is no other way to close the dialog box.

And that one way is to hit the Esc button on the keyboard which many viewers may not be able to guess if not specifically told.

If however you change the statement ‘closeOnClick: false’ to ‘closeOnClick: true’ (see the HTML code below), the dialog box can be closed by clicking anywhere on the page.

Whether or not the close option is provided, this delayed opening of an overlay dialog box is very popular among webmasters. The reasons are not far to seek.

Unlike the disturbing popup or the benign pop-under that can be easily dismissed or prevented, an overlay dialog box unfailingly arrests the attention of a viewer and is thus more successful for the purpose it is used.

The other reason is of course the sophistication of the technique, and one that catches eye no matter how indifferent or distracted a viewer is while surfing a webpage.

What is great about the whole thing is that the jQuery script used to design this overlay dialog box is available absolutely free. In this example the dialog box opens immediately upon loading of the webpage.

We have incorporated a delay event in the script (appearing toward the end of the HTML code, highlighted in blue color) that makes the overlay dialog box appear after a time gap. You can change this time to whatever you want.

You can also change the opacity, color, and speed of the overlay on which the dialog box appears. Feel free to copy the HTML code for your use.

If you are interested in more overlay designs, do look at the following video articles:

  1. How To Create Overlay Lightbox With jQuery Fancy-Zoom
  2. How To Create An Overlay Lightbox In Your Webpage

HTML Code

The HTML is easy and simple to use. The code below is complete and can be used for your needs. The script that calls the overlay to action is given just before the closing </body> tag. The main parameters in that code is highlighted for easy understanding. Feel free to copy the code for your use.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head>
	<title>jQuery Overlay Dialog Box With Delayed Opening</title>

	<script src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>	

</head>

<body>

<center><div style="font-family: lucida grande,tahoma,verdana,arial,sans-serif;width:500px;">
<h1>Example of Overlay Dialog Box</h1>
<p align=justify>This is an example of jQuery overlay dialog box with delayed opening. The delay is set at 7 seconds which can be altered easily. The dialog box opens atop a red overlay background, all of which can be changed in the code that appears at the bottom. You can also set the dialog box to open or not to open by clicking anywhere on the webpage.</p>
<p align=justify>To see the overlay effect again, simply refresh this page.</p>
</div></center>

<style>

#facebox {

	/* overlay is hidden before loading */
	display:none;

	/* standard decorations */
	width:400px;
	border:10px solid #666;

	/* for modern browsers use semi-transparent color on the border. nice! */
	border:10px solid rgba(82, 82, 82, 0.698);

	/* hot CSS3 features for mozilla and webkit-based browsers (rounded borders) */
	-moz-border-radius:8px;
	-webkit-border-radius:8px;
}

#facebox div {
	padding:10px;
	border:1px solid #3B5998;
	background-color:#fff;
	font-family:"lucida grande",tahoma,verdana,arial,sans-serif
}

#facebox h2 {
	margin:-11px;
	margin-bottom:0px;
	color:#fff;
	background-color:#6D84B4;
	padding:5px 10px;
	border:1px solid #3B5998;
	font-size:20px;
}

</style>

<!--[if IE]>
   <style>
   .facebox {
       background:transparent;
       filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#333333,endColorstr=#333333);
       zoom: 1;
    }
    </style>
<![endif]-->

<!-- facebook dialog -->
<div>

	<div>
		<h2>Subscribe To 2WebVideo Newsletter</h2>

		<p>Web professional? Remain updated with top tips and tricks every week. Invaluable info', guaranteed!</p>

		<!-- Begin Signup Form -->

		<form action="" method="post" target="_blank">
			<p>Your Email Address:<br />
			<input value="" style="margin-right: 5px;width: 60%;float: left;z-index: 999;">
			<input value="Subscribe" style="display: block;">
			</p>
		</form>

		<!--End Signup-->

		<p><button> Close This Box!</button></p>
	</div>

</div>

<script>

$(document).ready(function() {

// select the overlay element - and "make it an overlay"
$("#facebox").overlay({

	// custom top position
	top: 10,

	// some expose tweaks suitable for facebox-looking dialogs
	expose: {

		// you might also consider a "transparent" color for the mask
		color: '#F00',

		// load mask
		loadSpeed: 1000,

		// decide transparency
		opacity: 0.5
	},

	// disable this for modal dialog-type of overlays
	closeOnClick: false,

	// we want to use the programming API
	api: true

// load it after delay
})

var ol = $("#facebox").overlay({api: true});
  // wait 7 seconds, then load the overlay
  setTimeout(function() {
    ol.load();
  }, 7000);

});
</script>

</body>

février 18, 2010

Using JQuery to create dynamic HTML select elements.

Filed under: JQuery — izaam01 @ 11:15

This week I’m working a lot with JQuery and when searching for handling html select element I found little information about it, so I decide blog a little about this subject.

Typically you want add and remove options from a select box, so I setup a little page that does an append to a select and removes an option too.

We will have a Fruit Basket, we put a item in our hand and then eat it. Here’s the basket (listing 1):

 1 <html>
 2   <head>
 3     <script type=« text/javascript » src=« jquery.js »></script>
 4   </head>
 5   <body>
 6     <table>
 7        <tr>
 8          <td>
 9            Fruit Basket<br>
10            <select name=« basket » size=5 >
11              <option value=« apple »>Apple</option>
12              <option value=« banana »>Banana</option>
13              <option value=« orange »>Orange</option>
14              <option value=« grape »>Grape</option>
15              <option value=« starfruit »>Star Fruit</option>
16            </select><br>
17            <input type=« button » value=« Pickup » name=« pickup »>
18          </td>
19          <td>
20            Hand<br>
21            <select name=« hand » size=5 ></select><br>
22            <input type=« button » value=« Eat! » name=« eat »>
23          </td>
24        </tr>
25     </table>
26   </body>
27 </html>
This HTML is a simple one, the table was inserted just to put the selects side-by-side. Note that I didn’t put any javascript event handler like onClick(), onChange() and etc. This because with JQuery you can add the event handler very easily without cluttering the HTML.

Now comes the good stuff, insert a <script type="text/javascript"> tag and let’s see JQuery’s magic (listing 2).

 1 <script type=« text/javascript »>
 2 $(document).ready(function() {
 3   // the good stuff goes in here…
 4
 5   // when somebody clicks on Pickup…
 6   $(« input[name=’pickup’] »).click(function() {
 7
 8     // there’s something selected in our basket?
 9     if($(« select[name=’basket’] :selected »).length > 0) {
10
11       fruit_text   = $(« select[name=’basket’] :selected »).text();
12       fruit_value  = $(« select[name=’basket’] :selected »).attr(« value »);
13
14       // put the fruit in hand…
15       $(« select[name=’hand’] »).append(new Option(fruit_text, fruit_value));
16
17       // remove the fruit from the basket…
18       $(« select[name=’basket’] :selected »).remove();
19
20     } else { return false; } // don’t bother with a empty selection
21
22   });
23
24   // let’s eat!
25   $(« input[name=’eat’] »).click(function() {
26       $(« select[name=’hand’] :selected »).remove();
27   });
28
29 });
30 </script>
Now let’s explain what is happening.

If you already knows JQuery you recognize the line 2, this is a simple way to trigger your script when the document is ready, it’s a good practice. Insures that your script will not fire before the browser finished rendering all page elements.

In line 6 and 25 we define one anonymous (formally a lambda) function that will be fired on a click event for our both buttons. Pay attention on JQuery selector syntax it’s very important! In line 6 we say to JQuery:

$("input[name='pickup']")

and JQuery understand this:

"Give me the input element which has the attribute name equals to pickup."

If we were ambiguous in our selector JQuery will return more than one element, in this case we could iterate over the matches found with each() helper.

We ask to JQuery in line 9 if there’s something selected in our basket, if the length of selected fruits is greater than zero let’s do something.

We use some accessors from JQuery and save the text and the value of attribute « value » in two variables, lines 11 and 12. After that, in line 15, we tell JQuery to append a new Option object which is basically the same option selected in our basket.

Now the last step in this event is remove the fruit from the basket, one way to do this is calling remove() on the JQuery object.

If you payed attention on the above explanation lines 25 to 27 should be clear. We select what is selected on our hand and just « eat it » (in fact we remove the element). That’s it, simple and clean.

ajax

Filed under: JQuery — izaam01 @ 5:47

Prenons l’exemple suivant:

Charge et éxécute un fichier Javascript

$.ajax({ type: "GET", url: "test.js", dataType: "script" })

Prenons l’exemple suivant:

Charge les données de manière synchronisée. Blaoque le naviguateur tant que la requête est en cours Il est préférable de bloquer l’utilisateur d’autres manières quand la synchronisation est nécéssaire.

var html = $.ajax({ url: "some.php", async: false }).responseText;

Prenons l’exemple suivant:

Envoie des données au serveru et informe l’utilisateur des que l’opération est terminée.

$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " +msg ); } });

Prenons l’exemple suivant:

Envoi un document XML au serveur. En envoyant la paramètre processData=false, la conversion automatique des données sera empêchée.

var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: handleResponse });

Mon code
Supprimer une occurence et recharger le fichier

$.ajax({ type: "POST",
             url: "DB_supprecurrentes.php",
                  data: "liste="+valCheckbox  ,
               success: function(msg){ location.reload(); } 
});

:selected Selector

Filed under: JQuery — izaam01 @ 5:02

Description: Selects all elements that are selected.

The :selected selector works for elements. It does not work for checkboxes or radio inputs; use :checked for them.

Example:
Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.


Flowers Shrubs Trees Bushes Grass Dirt
//

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select name="garden" multiple="multiple">

    <option>Flowers</option>
    <option selected="selected">Shrubs</option>
    <option>Trees</option>
    <option selected="selected">Bushes</option>

    <option>Grass</option>
    <option>Dirt</option>
  </select>
  <div></div>
<script>

    $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .trigger('change');
</script>
</body>
</html>

Older Posts »

Créez un site Web ou un blog gratuitement sur WordPress.com.