Labels

Thursday, December 17, 2009

Quick JQuery

 

Selectors

$("body > div:has(img)")

 

//Select selected input items

$(":input:checked")

$("input:not(:checkbox)")

div p:not(:hidden)

 

// anchor tag starts with http://

$("a[href^=http://]")

$("a[href*=jquery.com]")

$("li:has(a)")

 

$("img:only-child")

 

$(function() {

$("table tr:nth-child(even)").addClass("striped");

});

 

//selects all even <p> elements.

$("p:even");

 

//selects direct <div> children of <body>.

$("body > div");

 

$('[name=radioGroup]:checked') .val(true)

 

Slicing

$('img[alt],img[title]')

$('img[alt]').add('img[title]')  // Same as comma in above

$('img[alt]').addClass('thickBorder').add('img[title]').addClass('seeThrough')

$('img[title]').not('[title*=puppy]')   // Except Behaviour

$('*').slice(4);

$('*').slice(2,3);

 

Filtering

$("li:has(a)")

$("tr td:contains(Java)")

$("input:not(:checkbox)")

 

var hasImage = $('*').is('img');

$("<div class='foo'>I have foo!</div><div>I don't</div>").filter(".foo")

$('td').filter(function(){return this.innerHTML.match(/^\d+$/)})

$("wrappedSet").find('p cite')

$('img[title]').not('[title*=puppy]')

 

 

 

Manipulation

$("<div class='foo'>I have foo!</div><div>I don't</div>")

.filter(".foo")

.click(function() {alert("I'm foo!");})

.end()

.appendTo("#someDiv");

 

$('p').append('<b>some text<b>');

$('img').clone().appendTo('#someDiv').addClass('beenCloned'); // Applies to Cloned

$('img').clone().appendTo('#someDiv').end().addClass('beenCloned'); // Applies to Original

$('img').clone().appendTo('#someDiv').andSelf().addClass('beenCloned'); // Applies to Original & Clonned both

 

var toAppend = $("a.appendMe")[0];

$("p.appendToMe").append(toAppend);

 

$('<p>Hi there!</p>').insertAfter('p img');

 

$("a.surprise").wrap("<div class='hello'></div>")

 

$("div.elementToReplace").after("<p>I am replacing the div</p>").remove();  // Place the ‘div’ after ‘p’ and remove from the original place

 

$.fn.replaceWith = function(html) {

return this.after(html).remove();

};

$("div.elementToReplace").replaceWith("<p>I am replacing the div</p>");

 

$('ul').clone().insertBefore('#here')

$('ul').clone().insertBefore('#here').end().hide(); // Atter the insertion of the clones, the end() command is used to select the original targets and hide them.

 

 

 

JQuery Object Accessor

$('img').each(function(n){

this.onclick=function(){alert('Hello');};

});

 

 

var allAlts = new Array();

$('img').each(function(){

allAlts.push(this.alt);

});

 

function DisableDIV() {

    $('div').each(function() { this.disabled = true;});

}

 

Attributes

$("#myImage").attr("custom")

 

$('*').attr('title',function(index) {

return 'I am element ' + index + ' and my name is ' + (this.id ? this.id : 'unset');

});

 

$('input').attr({ value: 'MyValue', title: 'Please enter a value' });

 

$("a[href^=http://]").attr("target","_blank");

 

$("form").submit(function() {

$(":submit",this).attr("disabled", "disabled");

});

 

 

function swap() {

$('tr').toggleClass('striped');

}

<table onmouseover="swap();" onmouseout="swap();">

 

$.fn.getClassNames = function() {

if (name = this.attr("className")) {return name.split(" ");}

else {return [];}

};

 

$('#display').html()

$('#display').html(‘<b>Hello</b>’)

 

var text = $('#theList').text();  // Returns innerText than the HTML

var text = $('#theList').text(‘Hello’);  // Returns innerText than the HTML

 

if($('[name=radioGroup]:checked').val() == false)

{

   $('[name=radioGroup]:checked') .val(true)

}

 

$('input,select').val(['one','two','three']); // Search all the <input> and <select> elements with values that match any: one, two or three. Any check boxes or radio buttons that are found to match will become checked, and any options that match will become selected.

 

 

CSS

$("div.expandable").css("width",function() {

return $(this).width() + 20 + "px";

});

 

$("div.myElements").css("width","500px")

$("#Div1").css("background-color", "Blue");

 

$("div.myElements").width(500)

 

function report() {

$('#display').html($('#testSubject').width()+'x'+$('#testSubject').height());

}

<body onresize="report();">

 

Traversing

 

$("p:first").hasClass("surpriseMe") // return bool

$("p:first").is(".surpriseMe") // Same as ‘has’

 

 

Events

$(function(){

$('#vstar')[0].onmouseover = function(event) {alert('Whee!');}

});

 

$(function(){

$('*').each(function(){

var current = this;

this. onclick = function(event) {

if (!event) event = window.event;

var target = (event.target) ? event.target : event.srcElement;

alert('For ' + current.tagName + '#'+ current.id + ' target is ' + target.id);

}

});

});

 

$(function(){

$('#vstar')

.bind('click',function(event) { alert ('Whee once!');})

.bind('click',function(event) { alert ('Whee twice!');})

.bind('click',function(event) { alert ('Whee three times!');});

});

 

$('#thing1').bind('click.editMode', someListener);

$('#thing2').bind('click.editMode', someOtherListener);

 

// Possible Events

blur

error

keyup

mouseout

scroll

change

focus

load

mouseover

select

click

keydown

mousedown

mouseup

submit

dblclick

keypress

mousemove

resize

unload

 

$('#thing1').one('click.editMode', someListener);  // Will React just once.

 

$(function(){

$('#vstar').toggle(function(event) {$(event.target).css('opacity',0.4);},function(event) {$(event.target).css('opacity',1.0);});

});

 

$('#outer2').hover(report,report);

function report(event) {

$('#console').append('<div>'+event.type+'</div>');

}

 

Chap -5

$(function(){

$('li:has(ul)').click(

            function(event)

            {

                        if (this == event.target)

                        {

                                    if ($(this).children().is(':hidden')){

                                                $(this).css('list-style-image','url(minus.gif)').children().show(); // .slideDown()

                                    }

                                    else {

                                                $(this).css('list-style-image','url(plus.gif)').children().hide();// .slideUp()

                                    }

                        }

            return false;

            }

            ).css('cursor','pointer').click();

 

$('li:not(:has(ul))').css({cursor: 'default','list-style-image':'none'});

});

 

 

$(function(){

$('li:has(ul)').click(

            function(event)

            {

                        if (this == event.target)

                        {

                                    $(this).children().toggle();

                                    $(this).css('list-style-image',($(this).children().is(':hidden')) ?'url(plus.gif)' : 'url(minus.gif)');

                        }

                        return false;

            }

)

.css('cursor','pointer').click();

 

$('li:not(:has(ul))').css({cursor: 'default','list-style-image':'none'});

});

 

 

$('.animateMe').each(function(){

$(this).animate(

{

            width: $(this).width() * 2,

            height: $(this).height() * 2

},

2000

);

});

 

$('.animateMe').each(function(){

$(this).css('position','relative')

.animate(

{

            opacity: 0,

            top: $(window).height() - $(this).height() - $(this).position().top

},

'slow', function(){ $(this).hide(); });

});

 

var target = (event.target) ? event.target : event.srcElement;

 

Utilities

var ie = $.browser.msie;  // True for IE

var fx = $.browser.mozilla; // True for Mozilla

 

<script type="text/javascript">

$(function(){

$('#loadButton').click(function(){$.getScript('new.stuff.js'//,function(){$('#inspectButton').click()});});

$('#inspectButton').click(function(){someFunction(someVariable);});

});

</script>

 

var anArray = ['one','two','three'];

$.each(anArray,function(n,value) {//do something here});

 

var bigNumbers = $.grep(originalArray,function(value) {return value > 100;});

var oneBased = $.map([0,1,2,3,4],function(value){return value+1;});

var index = $.inArray(2,[1,2,3,4,5]);

 

 

AJAX

var xhr;

if (window.XMLHttpRequest) {

xhr = new XMLHttpRequest();

}

else if (window.ActiveXObject) {

xhr = new ActiveXObject("Msxml2.XMLHTTP");

}

else {

throw new Error("Ajax is not supported by this browser");

}

 

xhr.onreadystatechange = function() {

            if (xhr.readyState == 4) {

                        if (xhr.status >= 200 && xhr.status < 300) {

                        document.getElementById('someContainer').innerHTML = xhr.responseText;

                        }

            }

}

xhr.open('GET','/serverResource');

xhr.send();

 

-------------------------------------------------------------------------------------

$('#someContainer').load('/serverResource');  // equivalent code to above – in one line

 

$(function(){

$('#styleDropdown')

.change(function(){

            var styleValue = $(this).val();

            $('#detailsDisplay').load('getDetails.jsp',{ style: styleValue });

            }

)

.change();

});

 

function Fire$Load()

 {

     $("#ShowDetailsDiv").load("Test$AJAX.aspx","name=John&location=Boston",function(msg) {alert(msg);});

 }

 

<script type="text/javascript">

$(function(){

$('#testButton').click(function(){

$.get('reflectData.jsp',{a:1, b:2, c:3},function(data) { alert(data); });

});

});

</script>

 

$.getJSON('getSizes.jsp',{style:styleValue,color:colorValue},function(data){$(dropdownSet).loadSelect(data)});

 

--------------------------------------------------------------------------------

function Fire$getScript() {

    $.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js",

                function() {              

                          $(".block").animate({ backgroundColor: 'pink' }, 1000).animate({ backgroundColor: 'blue' }, 1000);

                         });

   

}

 

<style>

        .block

        {

            background-color: blue;

            width: 150px;

            height: 70px;

            margin: 10px;

        }

    </style>

<div class="block"></div>

------------------------------------------------------------------------------------

 

 

$('#goodButton').click(function(){$.get('reflectData.jsp');});

$('#badButton').click(function(){$.get('returnError.jsp');});

$('#successDisplay').ajaxSuccess(function(info){$(info.target).append('<div>Success at '+new Date()+'</div>');});

$('#errorDisplay').ajaxError(function(info,xhr){

            $(info.target).append('<div>Failed at '+new Date()+'</div>')

                                 .append('<div>Status: ' + xhr.status + ' ' +xhr.statusText+'</div>');

            });

 

-----------------------------------------

function Fire$AJAX()

    {

        $.ajax({

                type: "GET",

                url: "Test$AJAX.aspx",

                data: "name=John&location=Boston",

                success: function(msg) {alert("Data Saved: " + msg);}

 

            });

    }

 

Test$AJAX.aspx :

protected void Page_Load(object sender, EventArgs e)

    {

        string name = Request.QueryString["name"].ToString();

        string location = Request.QueryString["location"].ToString();

 

        Response.Write("Data Found \n" + "Name: " + name + "\n" + "Location: " + location + "\n");

    }

-----------------------------------------

 

 

Also see code in table below at bullet 1.

 

 

 

 

 

 

 

 

1

<script type="text/javascript">

 

$(function() {

    $('#styleDropdown').change(

                                        function() {

                                                var styleValue = $(this).val();

                                                $('#detailsDisplay').load('getDetails.jsp', { style: styleValue });

                                                adjustColorDropdown();

                                        }

                            )

                .change();

 

    $('#colorDropdown').change(adjustSizeDropdown);

}

);

 

function adjustColorDropdown() {

    var styleValue = $('#styleDropdown').val();

    var dropdownSet = $('#colorDropdown');

    if (styleValue.length == 0) {

            dropdownSet.attr("disabled", true);

            $(dropdownSet).emptySelect();

            adjustSizeDropdown();

    }

    else {

            dropdownSet.attr("disabled", false);

            $.getJSON('getColors.jsp', { style: styleValue }, function(data) { $(dropdownSet).loadSelect(data); adjustSizeDropdown(); });

    }

}

 

function adjustSizeDropdown() {

    var styleValue = $('#styleDropdown').val();

    var colorValue = $('#colorDropdown').val();

    var dropdownSet = $('#sizeDropdown');

    if ((styleValue.length == 0) || (colorValue.length == 0)) {

            dropdownSet.attr("disabled", true);

            $(dropdownSet).emptySelect();

    }

    else {

            dropdownSet.attr("disabled", false);

            $.getJSON('getSizes.jsp', { style: styleValue, color: colorValue }, function(data) { $(dropdownSet).loadSelect(data) });

    }

}

</script>

 

 

 

 

 

No comments:

Post a Comment