JQuery custom function
From w3cyberlearnings
- You need a custom function in jQuery to do validate or to check information from other sources
- jQuery functions can be reused and make your jQuery codes less messy
jQuery function example
- This is a basic function in jquery.
- It displays hi when page load.
<script> $(document).ready(function(){ var sayHi=function(){ alert('hi'); } sayHi(); }); </script>
javascript style function
- You also can write the same function using javascript style.
<script> $(document).ready(function(){ function sayHi() { alert('hi'); } // call the sayHi() function sayHi(); }); </script>
jQuery function with argument
- This is similar to the previous function.
- But this function can have the parameter.
- When you load this function, it display good day!.
<script> $(document).ready(function(){ var sayHi=function(string){ alert(string); } sayHi("good day!"); }); </script>
javascript function version
<script> $(document).ready(function(){ function sayHi(string) { alert(string); } sayHi("God this is javascript style"); }); </script>
jQuery function assign error or message to the DIV
- jQuery function can be used to assign to the HTML element such as DIV ELMENT.
- In this example, the sayError() function with a parameter: pa_string.
- It is also using the jQuery css function to set the CSS stylesheet to the DIV ELEMENT.
- It displays "You got an error!!!" with the text in red color.
<script> $(document).ready(function(){ var sayError=function(pa_string){ $('div.my_test').html(pa_string).css('color','red'); } sayError("You got an error!!!"); }); </script> <div class="my_test"></div>
javascript function version
<script> $(document).ready(function(){ function sayError(pa_string) { $('div.my_test').html(pa_string).css('color','red'); } sayError("You got an error!!!"); }); </script>
jQuery function with a condition
- This is a very basic jquery function that uses if, else if condition.
- In the example, when the page loads it displays an alert:yes.
<script> $(document).ready(function(){ var checkCondition=function(condition){ if(condition=="yes"){ alert("yes"); } else if(condition=="no") { alert("no"); } else if(condition=="good") { alert("good"); } else { alert(condition); } } var my_condition = checkCondition("yes"); }); </script>
$.fn.extend() vs. $.extend()
- $.extend() is for received a single object, to add methods to the jQuery or jQery.fn
- $.fn.extend() is for function or methods.
$.fn.extend() example 1
- Set text
<script> $(document).ready(function(){ $.fn.extend({ sayError:function(){ $(this).html("Good !!!"); } }); // test $('div.my_test').sayError(); }); </script> <div class="my_test"></div>
$.fn.extend() example 2
- Setbackground
<script> $(document).ready(function(){ $.fn.extend({ setBackgroundColor:function(value){ $(this).css("background-color",value); } }); // test $('div.my_test').html("my world").setBackgroundColor("green"); }); </script>