Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Friday, July 29, 2011

JQuery sortable draggable bug.

JQuery sortable Update event calls twice when you bind it to class, not to id and when you drag item to other connectable block.
Jquery
$(".MyClass1, .MyClass2").sortable({
    connectWith: ".connectedSortable",
    update: function (event, ui) {
                alert("twice!");
            }})


Very simple solution is to change event "update" to "stop":

Jquery
$(".MyClass1, .MyClass2").sortable({
    connectWith: ".connectedSortable",
    stop: function (event, ui) {
                alert("once!");
            }})

Thursday, April 21, 2011

JQuery clone elements

TASK:
Clone DOM elements.

SOLUTION:
Use .clone() and .appendTo().

EXPLANATION:

In the following example we copy DOM element ".from_to_copy" to ".where_to_copy" without typed data and without javascript's bindings.

JQuery
$(".from_to_copy").clone().appendTo(".where_to_copy");

In this example we copy DOM element with data typed and javascript's bindigs.
JQuery
$(".from_to_copy").clone(true).appendTo(".where_to_copy");

Just change default ".clone()" to ".clone(true)".

Monday, April 18, 2011

JQuery detection of browser

TASK: 
Fix something or do special instructions according to browser type.
SOLUTION: 
Use the flags of $.browser:

  • $.browser.webkit
  • $.browser.safari (deprecated) 
  • $.browser.opera
  • $.browser.msie
  • $.browser.mozilla


Also, we can detect version of browser using $.browser.version

Jquery.browser and $.browser are synonymous.

EXAMPLE: 

JQuery
if ($.browser.mozilla)
{
alert("The browser is mozilla");
}

JQuery
if ($.browser.msie)
{
alert("The browser is Internet Explorer, version:" + $.browser.version);
}

Wednesday, April 13, 2011

JQuery select element at index n

TASK:
Select the element at index n within the matched set.


SOLUTION:
$(".example:eq("+index+")").css("color", "red");

EXAMPLE:
Select element at index 1 and set css property "color" to "red":
JQuery
var index=1;
$(".example:eq("+index+")").css("color", "red");

HTML
<div class="example">div index 0</div>
<div class="example">div index 1</div>
<div class="example">div index 2</div>

JQuery index of element

TASK:
Recognize index of element in group on which we clicked.
SOLUTION: 
$("#parent child").index(this);
EXAMPLE:

JQuery
$(document).ready(function() {

    $("#example div").click(function() {
        var index = $("#example div").index(this);
        $("#example_index").html("Index " + index + " was clicked");
    });

});

HTML
<div id="example">
    <div>div index 0</div>
    <div>div index 1</div>
    <div>div index 2</div>
    <div>div index 3</div>
    <div>div index 4</div>
</div>
<div id="example_index">Click one of the above divs</div>