Oct
9
9
I’m planning to post some jQuery code snippets in this category. It’s usefull to have such a small parts of a code in your personal library and don’t waste time coding or googling it.
How to center element in browser window.
jQuery.fn.center = function() { var w = $(window); this.css("position","absolute"); this.css("top",(w.height()-this.height())/2+w.scrollTop() + "px"); this.css("left",(w.width()-this.width())/2+w.scrollLeft() + "px"); return this; } |
Now we can just write:
$(element).center(); |
and object will be centerd.
Open this example in new window and view source code.
How to make entire block of code clickable.
Javascript code:
$(".pane-list li").click(function(){ window.location=$(this).find("a").attr("href");return false; }); |
…and some html code:
<ul class="pane-list"> <li> <h3><a href="http://www.jquery.com">jQuery homepage</a></h3> <p>This is jQuery homepage</p> </li> <li> <h3>Google</h3> <p>This is a best search engine - <a href="http://www.google.com">Google!</a></p> </li> </ul> |
Open this example in new window and view source code.
How to select all checkboxes inside the form.
This function will select all checkboxes in the given element (div, for example). We pass element id as an argument:
function checkall(context){ $("#"+context).find("input[@type=checkbox]").each(function(){ this.checked = "checked"; }); } |
In this example only Checkbox #1 and Checkbox #2 will be selected because they are inside div with id “myboxes”:
<script type="text/javascipt">checkall("myboxes");</script> |
<div id="myboxes"> Form #1:<br> <form action="" method="GET"> <input type="checkbox" name="cb1">Checkbox #1 <input type="checkbox" name="cb2">Checkbox #2 </form> </div> Form #2:<br> <form action="" method="GET"> <input type="checkbox" name="cb3">Checkbox #3 <input type="checkbox" name="cb4">Checkbox #4 </form> |
Open this example in new window and view source code.
How to find out quantity of selected elements.
Just like this:
$('element').size(); |
How to find out if some element present on page.
You can just check length value:
if ( $('element').length ) { /* do something */} |
Alex
Add A Comment