1 / 48

jQuery $( document).ready alternatives

jQuery $( document).ready alternatives. http:// rdjs.co.uk/jquery-document-ready-alternatives/53. jQuery – Document Ready . An alternative to body onload .  $(document).ready(function() {      // do stuff when DOM is ready });

arin
Télécharger la présentation

jQuery $( document).ready alternatives

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. jQuery $(document).ready alternatives http://rdjs.co.uk/jquery-document-ready-alternatives/53

  2. jQuery – Document Ready  • An alternative to body onload.  • $(document).ready(function() { •      // do stuff when DOM is ready • }); • jQuery(document).ready(function($) {    //do jQuery stuff when DOM is ready}); • Adding the jQuery can help prevent conflicts with other JS frameworks. • jQuery in the no-conflict mode means that $ is not the jQuery object/namespace

  3. alternatives to $(document).ready • Use shorthand • $(function(){ • // your code here • }); • This works in exactly the same way as the standard $(document).ready function and has the added benefit of being more concise • BUT it can be harder to read • jQuery(function( $ ){ • //Insert your javascript code here • });

  4. alternatives to $(document).ready • You can embed a function inside a function so that both use the $ as a jQuery alias. • (function($) { • // code using $ as alias to jQuery • $(function() { • // more code using $ as alias to jQuery • }); • })(jQuery); • // other code using $ as an alias to the other library

  5. alternatives to $(document).ready • Use chaining • $().ready(function(){ • console.log("the document is ready") • }); • Chain a jQuery ready() function to the return value of the jQuery object: $().ready(). When the jQuery object is ready, so is the code.

  6. alternatives to $(document).ready • Don’t use an anonymous function • $(document).ready(fooBar); • function fooBar() • { • // Your code here • } • Explicitly state the function to execute when the DOM has finished loading. • Still using the normal jquery $(document).ready syntax but the fooBar function is called instead of using an anonymous function. • The result is the same but the opening and closing brackets are less untidy.

  7. alternatives to $(document).ready • On ‘Window’ load • There is a lesser known option that waits for the whole page to load, including images. This is in comparison to normal • $(document).ready which just waits for the DOM to load. • $(window).load(function(){ • // Your code here • }); • This obviously has its advantages if you need absolutely everything to have finished loading before your JavaScript runs. • For everyday use however you will probably run into problems where your scripts will not work until all the assets have finished loading. • This may annoy your users who will be wanting to interact with the page before it is ready.

  8. alternatives to $(document).ready • Don’t use $(document).ready at all • There is a small performance hit in using $(document).ready so, if the code you have written does not need the DOM to have finished loading, consider not using the $(document).ready function at all. • This seems like a risky strategy however for a marginal speed improvement. • Additionally current wisdom suggests moving your JavaScript code to the end of the page, mainly for the speed improvements. • An interesting side-effect of moving your JavaScript to the end of the page is that $(document).ready is often no longer necessary. • It is important to remember that not all code can be moved to the bottom of the page, document.write calls for example are problematic.

  9. Best option? • Unless you are completely clear about the advantages & risks of each method • Stick to using the original $(document).ready function • or • the shorthand alternative.

  10. JQuery - multiple $(document).ready …? • Recommended that you not have more than one$(document).ready function per document • If you have more, all will get executed on a first Called, first Run basis! • Execution is top-down, sequential. • If execution sequence is important, combine them. • *Best practise: Use only one whenever possible. • You can link to multiple external javascript files that each have their own $(document).ready functions

  11. jQuery.noConflict() – Multiple Javascript Libraries

  12. Why do conflicts happen? • Conflicts typically happen because many JavaScript Libraries/Frameworks use the same shortcut name which is the dollar symbol $. Then if they have the same named functions the browser gets confused!

  13. jQuery – Conflicts • Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. • If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():  • <script type="text/javascript" src="other_lib.js"></script> •  <script type="text/javascript" src="jquery.js"></script> • <script type="text/javascript"> $.noConflict(); • // Code that uses other library's $ can follow here. • </script>

  14. How do we prevent conflicts? • Alias the jQuery namespace (ie by using jquery). • When you call $.noConflict() to avoid namespace difficulties (as the $ shortcut is no longer available) thiss forces the writing of jQuery each time it is required. • jQuery.noConflict(); // Reverts '$' variable back to other JS libraries • jQuery(document).ready( function(){ • //do jQuery stuff when DOM is ready with no conflicts • }); • //or the self executing function way • jQuery.noConflict(); • (function($) { • // code using $ as alias to jQuery • })(jQuery);

  15. jQuery – Conflicts • Use noConflict to prevent the $ from conflicting with other JavaScript libraries. • jQuery.noConflict();(function($) {  $(function() {   // by passing the $ you can code using the $ alias for jQuery   alert('Page: ' + $('title').html() + ' dom loaded!');  });})(jQuery);

  16. Forms As always with programming, there's more than one way to do it.

  17. jQuery: Test/check if input field is empty • Test if input field is has a value. • or is empty • <input type="text" id="myinputA" value=""/> • <input type="text" id="myinputB" value="some text"/> Syntax: $(selector).val() If the element doesn't exist it will return 'undefined' and if it does but has null value or has no length it will return "" -- all of which evaluate as false in if statements • if($('#myinputA').val()){ • //do something • } • if (!$('#myinputA').val().length) { • //do stuff • } • if ($('#myinputA').text().length() == 0){ • // action • }

  18. jQuery: Test/check if input field is empty • Set the value of the <input> field: • $("#submitbtn").click(function(){ • $("input:text").val("Other Value"); • }); • $("#submitbtn").click(function(){ • //do something • $('#myinputA').val("Other Value"); • });

  19. jQuery: Test/check if checkbox is checked • Test if checkbox has checked property set. • Using jQuery version 1.6 or newer • jQuery version 1.6 introduced .prop() method to get HTML/DOM element’s property • Recommended: To check the checked property of an element use the .prop() method <input id="checkbox"  type="checkbox" name="one" value="1" checked="checked"> <input id="checkbox2" type="checkbox" name="two" value="2"> <input id="checkbox3" type="checkbox" name="three" value="3">

  20. jQuery: Test/check if checkbox is checked • Four methods of checking // First method - Recommended $('#checkbox').prop('checked') // Boolean true // Second method - Makes code more readable (e.g. in if statements) $('#checkbox').is(':checked') // Boolean true // Third method - Selecting the checkbox & filtering by :checked selector $('#checkbox:checked').length // Integer >0 $('#checkbox:checked').size() // .size() can be used instead of .length // Fourth method - Getting DOM object reference $('#checkbox').get(0).checked // Boolean true $('#checkbox')[0].checked // Boolean true (same as above) http://jquery-howto.blogspot.com/2013/02/jquery-test-check-if-checkbox-checked.html

  21. jQuery: Test/check if radio button is checked • Test if radio button has checked property set. • Similar to checkbox • <form action=""> • <input type="radio" name="examGroup" id="test1" value="59" /> <label for="test1">Test 1</label> • <input type="radio" name="examGroup" id="test2" value="82" /> <label for="test2">Test2</label> • <input type="radio" name="examGroup" id="test3" value="43" /> <label for="test2">Test3</label> • <input type="submit" id="submitbtn" value="Submit"> • </form>

  22. jQuery: Test/check if checkbox is checked // First method - Recommended varisChecked = $('#radioButton').prop('checked'); // Boolean true // Second method - Makes code more readable (e.g. in if statements) • $('#radioButton').is(':checked') // Boolean true • varisChecked = $('#radioButton').is(':checked'); // Third method - Selecting the checkbox & filtering by :checked selector • $('#radioButton:checked').length // Integer >0 • $('#radioButton:checked').size() // .size() can be used instead of .length • varisChecked = $('#radioButton :checked').val()?true:false; • $('#radioButton:checked').val() method returns "on" when radio button is checked and "undefined", when radio button is unchecked. // Fourth method - Getting DOM object reference • $('#radioButton').get(0).checked // Boolean true • $('#radioButton')[0].checked // Boolean true (same as above) • Four methods of checking

  23. jQuery: Test/check if radio button is checked • Check a single radio button, upon submit or some event, to see if the radio button was checked or not. • $('#element').click(function() { • if($('#radio_button').is(':checked')) { • alert("it's checked"); • } • }); • $('#test2').is(':checked'); • $('input:radio[name=radioGroup]:checked').val() == 'value' • $('input:radio[name=examGroup]:checked').val() == 'test2';

  24. jQuery: Test/check if radio button is checked • Check a group of radio buttons sharing the same name attribute, upon submit or some event, to see if one of the radio buttons was checked or not. • $(document).ready(function(){ • $('#submitbtn').click(function() { • if (!$("input[name='name']:checked").val()) { • alert('Nothing is checked!'); • return false; • } • else { • alert('One of the radio buttons is checked!'); • } • }); • });

  25. jQuery: Test/check if radio button is checked • Find all radio buttons checked • $("input[type=radio][checked]").each( • function() { • // Your code goes here... • } • );

  26. jQuery: Test/check if radio button is checked • Check if no radio button in a group has been checked • if ($("input[name='examGroup']:checked").val() == "") { • alert('Nothing is checked!'); • } • else { • alert('One of the radio buttons is checked!'); • } • $("input:radio[name=‘examGroup']").is(":checked") • This will return FALSE if all the items in the radio group are unchecked and TRUE if an item is checked. • if ($('input[name=“examGroup"]:checked').length === 0) { • alert("Not checked"); • } • else { • alert("Checked"); • }

  27. jQuery: Test/check if radio button is checked • To get the currently selected radio button's id: • varid = $("input[@name=testGroup]:checked").attr('id'); • To get the currently selected radio button's value: • var value = $("input[@name=testGroup]:checked").val(); • $(document).ready(function () { • $("#submitbtn").click(function () { • var number = $("input[@name=examGroup]:checked").val(); • alert(number); • }); • });

  28. jQuery: Test/check if select list option is selected • Test if option is selectedproperty set. • <form action=""> • <select id="mySelect" multiple="multiple"> • <option value="1">First</option> • <option value="2">Second</option> • <option value="3">Third</option> • <option value="4">Fourth</option> • </select> • <input type="submit" id="submitbtn" value="Submit"> • </form>

  29. jQuery: Test/check if select list option is selected • Check a select list to see if an option was selected or not. • $('#mySelect option').each(function() { • if($(this).is(':selected')) //could also be written as ‘if (this.selected)’ • alert('this option is selected'); • else • alert('this is not'); • }); • $('#mySelect option').each(function() { • if ($(this).prop("selected") == true) { //could also be written as ‘if (this.selected == true) {’ • // do something • } else { • // do something • } • });

  30. jQuery: Test/check if select list option is selected • To get the currently selected option’s value: • var selected_option = $('#mySelect option:selected'); • The value of the selected option: • $('#mySelect').val() • The text of the selected option: • $('#mySelect option').filter(':selected').text(); • $('#mySelect>option:selected').text(); • var result= $("#mySelectoption:selected").text(); • To Set Select Option Value • $('#mySelect').val('newValue'); • To test for a particular option value 'myoption': • if($("#mySelectoption:selected").text() == myoption){ • //... • } • To get/set the actual selectedIndex property of the select element use: • Get -> $("#select-id").prop("selectedIndex"); • Set -> $("#select-id").prop("selectedIndex",1);

  31. jQuery: Test/check if select list option is selected • Detect the current or default selection. • <form action=""> • <select id="mySelect" multiple="multiple"> • <option id="v1" value="1">First</option> • <option id="v2" value="2">Second</option> • <option id="v3" value="3" selected>Third</option> • <option id="v4" value="4">Fourth</option> • </select> • <input type="submit" id="submitbtn" value="Submit"> • </form>

  32. jQuery: Test/check if select list option is selected • To get the current selection - use the :selectedselector: • $('select').find('option').filter(':selected'); • or • $('select').find('option:selected'); • To get the default selection: • $('select').find('option[selected]'); • $('select').find('option').filter('[selected]');

  33. jQuery: Test/check if select list option is selected • Detect when an option with a specific id is selected. • <form action=""> • <select id="mySelect" multiple="multiple"> • <option id="v1" value="1">First</option> • <option id="v2" value="2">Second</option> • <option id="v3" value="3">Third</option> • <option id="v4" value="4">Fourth</option> • </select> • <input type="submit" id="submitbtn" value="Submit"> • </form>

  34. jQuery: Test/check if select list option is selected • Listen for the change event on the select list to fire and once it does check the id attribute of the selected option. • $("#mySelect").change(function(){ • var id = $(this).find("option:selected").attr("id"); //could also try .prop('id') • switch (id){ • case “v2": • // do something here • break; • } • }); .attr() and .prop() are not synonymous. They will work interchangeably in certain instances where an attribute is also a property, e.g. .attr('id') is equal to .prop('id').

  35. jQuery: Test/check if textarea is empty • Test if textareais empty. • if (!$("#mytextarea").val()) { • // textarea is empty • } • You can also use $.trim to make sure the element doesn't contain only white-space: • if (!$.trim($("#mytextarea").val())) { • // textarea is empty or contains only white-space • } • <textarea id="mytextarea"></textarea> • <div id="debug"></div>

  36. jQuery: Test/check if textarea is empty • Test if textareais empty. • Check the value of the textarealength to see if it has anything in it: • $("#mytextarea").bind("input", function () { • if (!$.trim($("#mytextarea").val())) { • // textarea is empty or contains only white-space • $("#debug").text("Empty"); • } • else • $("#debug").text("Not empty"); • }).trigger("input"); • or • var txt = $.trim( $('#mytextarea').val() ); • if(!txt){ •     // show the prompt... • } • if (!$('#mytextarea').val().length) { • //do stuff • } • or • if ($(#mytextarea).text().length() == 0){ • // action • }

  37. Assignment Due next week

  38. jQuery Tutorials for Creating and Working with Forms • http://designshack.net/tutorials/creating-a-slide-in-jquery-contact-form • http://corpocrat.com/2009/07/15/quick-easy-form-validation-tutorial-with-jquery/ • http://www.chromaticsites.com/blog/jquery-tutorial-selecting-multiple-select-form-elements-on-the-fly/ • http://www.camcloud.com/blog/jquery-form-validation-tutorial

  39. jQuery tooltip What is a Tooltip? Tooltip is a message that appears when a cursor is positioned over an image, icon, link or any other HTML element.

  40. Simple stylized tooltip using jQuery • The HTML MarkUp • This example will use the <a> hyperlink tags for the tooltips. The title attribute value will be used as text of the tooltip. • You can also have label or span tag, instead of hyperlink tag. But make sure that you include the specific attribute of the tag used. <a class="moreinfo" href="http://google.com" title="Mostly asked jQuery Interview Question">jQuery Interview Question</a> <br/><br/> <a class="moreinfo" href="http://google.com" title="Best 5 jQuery Captcha Plugins">jQuery Captcha Plugins</a> <br/><br/> <a class="moreinfo" href="http://google.com" title="Go to My Blog HomePage">My Blog</a>

  41. Simple stylized tooltip using jQuery • CSS • The tooltip appears next to the tag. This CSS class, will put the tooltip on absolute position, but also make it look like a box. <styletype="text/css"> • .tooltip { • display: none; • font-size: 10pt; • position: absolute; • border: 1px solid #000000; • background-color: #FFFFE0; • padding: 2px 6px; • color: #990000; • } • </style>

  42. Simple stylized tooltip using jQuery • jQuery • Use the "hover" function to show the tooltip. All the hyperlink tags are assigned a "moreinfo" class. Bind the the ".hover" function event to elements with the CSS class selector. The .hover method bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. $('.moreinfo').hover(function(event) { // Hover over code }, function() { // Hover out code });

  43. Simple stylized tooltip using jQuery • .hover() provides two handler events: mouseover and mouseout. • On mouseover create tooltip: • First, fetch the value of "title" attribute from the Hyperlink tag. • Create a dynamic SPAN tag with class="tooltip". Assign Tooltip variable value to this span tag. • Append the newly created span tag to body of the page and also set it top and left position with respect to current position of mouse. • Using event.X and event.Y, you can get mouse position coordinates. • And animate the span tag, so it looks good. • And on mouseout, simple remove the dynamically created span tag. $('.moreinfo').hover(function(event) { vartoolTip = $(this).attr(‘title'); $('').text(toolTip) .appendTo('body') .css('top', (event.pageY - 10) + 'px') .css('left', (event.pageX + 20) + 'px') .fadeIn('slow'); }, function() { $('.tooltip').remove(); });

  44. Simple stylized tooltip using jQuery • The tooltip should move along with the mouse, when you are moving the mouse over a hyperlink tag. To achieve this, change the top and left position of tooltip on mousemove. .mousemove(function(event) { $('.tooltip') .css('top', (event.pageY - 10) + 'px') .css('left', (event.pageX + 20) + 'px'); });

  45. Simple stylized tooltip using jQuery the complete jQuery code • <scripttype="text/javascript"> • $(document).ready(function() { • $('.website').hover(function(event) { • vartoolTip = $(this).attr('title'); • $('<span class="tooltip"></span>').text(toolTip) • .appendTo('body') • .css('top', (event.pageY - 10) + 'px') • .css('left', (event.pageX + 20) + 'px') • .fadeIn('slow'); • }, function() { • $('.tooltip').remove(); • }).mousemove(function(event) { • $('.tooltip') • .css('top', (event.pageY - 10) + 'px') • .css('left', (event.pageX + 20) + 'px'); • }); • }); • </script>

  46. More tooltip examples using jQuery • Example 1: JQuery Tooltip showing Text Message • mouseover on text and it will show tooltip showing a text message. <styletype="text/css"> .tooltip { margin: 8px; padding: 8px; border: 1px; background-color: #C11B17; position: absolute; color: white; font-family: verdana; font-weight: 10pt; z-index: 2; } </style> HTML <span style="cursor: pointer; cursor: hand; font-family: verdana; font-size: 9pt; font-weight: bold;" id="text">Mouseover to see Text Tooltip</span> <scripttype="text/javascript">    $(document).ready( function() { varchangePosition = function(event) { var X = event.pageX- 8; var Y = event.pageY + 8;                 $('div.tooltip').css({                   top : Y,                   left : X                 });               }; varshowTextTooltip = function(event) {                 $('div.tooltip').remove();                 $('<div class="tooltip">This is a Jquery Tooltip</div>')                         .appendTo('body'); changePosition(event);               }; varhideTooltip = function() {                 $('div.tooltip').remove();               };               $("span#text").bind({ mousemove : changePosition, mouseenter : showTextTooltip, mouseleave : hideTooltip               });             }); </script>

  47. More tooltip examples using jQuery • Example 1: JQuery Tooltip showing Image with Text • mouseover on text and it will show tooltip showing an image with a text message. <styletype="text/css"> .tooltip { margin: 8px; padding: 8px; border: 1px; background-color: #C11B17; position: absolute; color: white; font-family: verdana; font-weight: 10pt; z-index: 2; } </style> HTML <span style="cursor: pointer; cursor: hand; font-family: verdana; font-size: 9pt; font-weight: bold;" id="image">Mouseover to see Image Tooltip</span> <scripttype="text/javascript">    $(document).ready( function() { varchangePosition = function(event) { var X = event.pageX- 8; var Y = event.pageY + 8;                 $('div.tooltip').css({                   top : Y,                   left : X                 });               }; varshowImageTooltip= function(event) {    $('div.tooltip').remove();$('<div class="tooltip"><imgsrc="jquery_tooltip_showing_text_with_image.jpg"><br/><br/>This is Image Jquery Tooltip :)</div>').appendTo('body');changePosition(event);};        varhideTooltip = function() {                 $('div.tooltip').remove();               };               $("span#image").bind({ mousemove : changePosition, mouseenter : showImageTooltip, mouseleave : hideTooltip               });             }); </script>

  48. Resources • http://css-tricks.com/bubble-point-tooltips-with-css3-jquery/ • http://www.mkyong.com/jquery/how-to-create-a-tooltips-with-jquery/ • http://cssglobe.com/easiest-tooltip-and-image-preview-using-jquery/ • jQuery Cheatsheet from version 1.0 to 1.9 • http://oscarotero.com/jquery/

More Related