Lecture 7: Useful Index() Method of jQuery, text() method of jQuery, checking contents of a DOM element, 'Get, Set, Remove Atributes', Event Listeners, jQuery Effects, jQuery Plugin
Useful Index() Method of jQuery
<div id="nav"> <div>text 1</div> <div>text 2</div> <div>text 3</div> <div>text 4</div> <div> <script src="jquery-2.1.3.js"></script> <script> (function($){ $('#nav div').click(function(){ //click event listener alert($('#nav div').index(this));//pass DOM element to index method // alert($(this).prevAll().length);//use of prevAll method }); })(jQuery); </script>
text() method of jQuery
-Now add this line in the previous scriptalert($('div').text()); //alert($('div').text("he…; // try this too //alert($('div').text().addCla… abt this?- Using javascript's replace method
$div = $('div'); newText = $div.text().replace('text','word');//replace() works on the strings //the text hasn't been added to the HTML yet $div.text(newText);//content of div changes now //or $div.text($div.text().replace('text','word');
checking contents of a DOM element
<div>jQuery<strong>is very</strong>useful.</div> <script src="jquery-2.1.3.js"></script> <script> (function($){ alert($('div').contents().get(0).nodeValue);//nodeValue is a DOM property alert($('div').contents().eq(1).text());//text() is jQuery function alert($('div').contents().get(2).nodeValue);//get returns DOM object, not jQuery object //lets check this //alert($('div').contents().eq…); })(jQuery);</script>Remember: jQuery remove() also returns the jQuery object
<div>remove me</div> <script src="jquery-2.1.3.js"></script> <script> (function($){ $('div').remove().html('<a href="http://www.jQuery.com">jQuery<…; })(jQuery); </script>
Get, Set, Remove Atributes
var bId = $('p').attr('id');//gets id of first p tag only $('p').attr('id','new');//sets id of all p elements $('p').removeattr('class');//removes class attr from all p elements
//some useful jQuery atttributes $('#button').attr('disabled', 'disabled');//disables a button alert($('#button1').is(':enabled'));//checks if button is enabled alert($('button:enabled').length);//checks how many buttons are enabled alert($('#button2').is(':disabled'));//checks if a button is disabled $('input:checkbox,input:radio').attr('checked', 'checked');
Attributes of form elements
- Use val()<input type="radio" value="radio1"> <input type="radio" value="radio2"> <input type="checkbox" value="checkbox1"> <input type="checkbox" value="checkbox2"> <script src="jquery-2.1.3.js"></script> <script> (function($){ $('input:radio,input:checkbox').val(['radio1','checkbox2']); //checks the input if the values given in the array match $('input:checkbox').val('Check1');//sets new value to all checkboxes, but doesn't check alert($('input:checkbox:checked').length);//filters can be stacked alert($('input:checkbox').val());//gets value of first checkbox })(jQuery);</script>
Setting Getting other form elements
<select id="sel1"> <option value="option1">option one</option> <option value="option2">option two</option> </select> <select id="sel2" size="3" multiple="multiple"> <option value="option1">option one</option> <option value="option2">option two</option> <option value="option3">option three</option> </select> <script src="jquery-2.1.3.js"></script><script> (function($){ $('select #sel1').val('option2');//set the value in select element alert($('#sel1').val());//gets the selected value
$('#sel2').val(['option2', 'option3']);//set alert($('#sel2').val().join(', '));//get })(jQuery);</script>
Event Listeners
on() and off() adds and removes event listerners in jQuery$('input').on('click', function(){ alert('You clicked me!'); });list of events that goes with bind() and unbind()
blur focus load resize scroll unload beforeunload click dblclick mousedown mouseup mousemove mouseover mouseout change select submit keydown keypress keyup error
//jQuery custom events mouseenter mouseleave //you can also create your own event
jQuery('a').off('click'); //remove an event handler jQuery('a').off();//remove all event handlers from all anchorsTrigger the event yourself
$('a').click(function(event){ alert('hi') });//shortcut-adding event handler //shortcut works only for click(), mouseout() and focus() $('a').click();//triggers the event if no fucntion is passed //or $('a').trigger('click'); //works for all events
//also $('input').bind('click', function(){ alert('You clicked me!'); $('input').unbind('click'); });
Recall Event object
Event object Attributes - event.type - event.target - event.data - event.relatedTarget - event.currentTarget - event.pageX - event.pageY - event.result - event.timeStamp Event object Methods - event.preventDefault() - event.isDefaultPrevented() - event.stopPropagation() - event.isPropagationStopped() - event.stopImmediatePropagation() - event.isImmediatePropagationStopped()
More than one handler for same event
$(window).bind('click.handler1', function(){ alert('I am listener1'); }); $(window).bind('click.handler2', function(){ alert('I am listerner2'); }); $(window).unbind('click.handler2');//removes only handler2
//useful $('div').click(function(event){ return false; //return false stops propagation and prevent default behaviour too });
add event listener to elements not created yet
<button>Add another Button</button> <script src="jquery-2.1.3.js"></script> <script> (function($){ var count=0; $('body').on('click','button',function(){ $(this).after("<button>Add another Button</button>"); count++; if(count==10) $('body').off('click','button');//remove the event listener from all }); })(jQuery); </script>
jQuery Effects
$('div:first').click(function(){ $(this).slideUp('slow').slideDown('slow').hide(1000); });More effects method at https://api.jquery.com/category/effects/…
$('input:first').on("mouseover",function(){ $(this).animate({width:'200px'},1000).animate({borderWidth:'10px'},1000); });
jQuery Plugin
- Use $.fn or jQuery.fn object to create your own jQuery method (plugin)$.fn.greenify = function() { this.css( "color", "green" ); return this; } $( "a" ).greenify().addClass( "greenified" );Basic Instruction at https://learn.jquery.com/plugins/basic-p… Now lets make a plugin of our own!!!