Wednesday, September 28, 2011

JQuery Focus Event

In this article we will learn how JQuery focus events work

Focus event triggers whenever control receives focus.  Example: change textbox background color on textbox focus.

Example 1 - Focus Event: Change textbox background color on Focus (Live Demo)
I have a 3 html input control, whose id is "txtInput1", "txtInput2" and "txtInput3" on receiving focus it should change its background color to Yellow, Red and Green.


Input 1: <input id="txtInput1" type="text" /> <br /><br />
Input 2: <input id="txtInput2" type="text" /> <br /><br />
Input 3: <input id="txtInput3" type="text" /> <br /><br />

JQuery script for changing background color on receiving focus


<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#txtInput1").focus(
            function (event) {
                $("#txtInput1").css("background-color", "Yellow");
            }
        );


        $("#txtInput2").focus(
            function (event) {
                $("#txtInput2").css("background-color", "Red");
            }
        );


        $("#txtInput3").focus(
            function (event) {
                $("#txtInput3").css("background-color", "Green");
            }
        );
    });
</script>


Example 2 - FocusIn Event: FocusIn Event is similar to focus event.  Let try to Change textbox background color on Focus with focusin JQuery event (Live Demo)
I have a 3 html input control, whose id is "txtInput1", "txtInput2" and "txtInput3" on receiving focus it should change its background color to Yellow, Red and Green.


Input 1: <input id="txtInput1" type="text" /> <br /><br />
Input 2: <input id="txtInput2" type="text" /> <br /><br />
Input 3: <input id="txtInput3" type="text" /> <br /><br />

JQuery script for changing background color on receiving focus


<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#txtInput1").focusin(
            function (event) {
                $("#txtInput1").css("background-color", "Yellow");
            }
        );


        $("#txtInput2").focusin(
            function (event) {
                $("#txtInput2").css("background-color", "Red");
            }
        );


        $("#txtInput3").focusin(
            function (event) {
                $("#txtInput3").css("background-color", "Green");
            }
        );
    });
</script>

Example 3 - FocusOut Event: Change textbox background color on Focus out (Live Demo)
I have a 2 html input control, whose id is "txtInput1" and "txtInput2"  

Input 1: <input id="txtInput1" type="text" /> <br /><br />
Input 2: <input id="txtInput2" type="text" /> <br /><br />

JQuery script for changing background color on receiving focus
<script language="javascript" type="text/javascript">
    $(document).ready(function () {

        $("#txtInput1").focusin(

            function (event) {
                $("#txtInput1").css("background-color", "Yellow");
            }
        );


        $("#txtInput2").focusin(
            function (event) {
                $("#txtInput2").css("background-color", "Red");
            }
        );




        $("#txtInput1").focusout(
            function (event) {
                $("#txtInput1").css("background-color", "White");
            }
        );


        $("#txtInput2").focusout(
            function (event) {
                $("#txtInput2").css("background-color", "White");
            }
        );


    });
</script>


I will be discussing more JQuery examples in JQuery example series.

JQuery Select Event

In this article we will learn how JQuery select events work

The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.

Example 1: Show Alert when textbox value is selected using JQuery Select Event (Live Demo)
I have a html textarea control, whose id is "txtInput" on selecting content of textarea, I will display alert.

<textarea id="txtInput" rows="5" cols="20">Welcome to the world of JQuery</textarea>

JQuery script for showing alert on text content selection


<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#txtInput").select(
            function () {
                alert("Text content is selected");
            }
        );


    });
</script>



I will be discussing more JQuery examples in JQuery example series.

JQuery Change Event

In this article we will learn how JQuery change events work

Change event will fire, when value of element is getting changed.  Example:  If we try to change textbox value it should try to validate it.

Example 1: Show Alert when textbox value is changed using JQuery Change Event (Live Demo)
I have a html textbox control, whose id is "txtInput" on changing value of textbox content, I will display alert.

<b>Type anything in below textbox to trigger, change event</b><br />
<input id="txtInput" type="text" />

JQuery script for showing alert on text content change

<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#txtInput").change(
            function () {
                alert("Textbox value is changed");
            }
        );


    });
</script>


I will be discussing more JQuery examples in JQuery example series.

JQuery Keydown, Keypress and Keyup Event

In this article we will learn how JQuery keydown, Keypress and Keyup events work.

  • Keydown Event bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.
  • Keypress Event bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.
  • Keyup Event bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.
This events are very similar and you will find very minor difference between them.  To  understand difference between Keydown, Keypress and Keyup event is sequence in which they triggers.
  • First Keydown Event occurs (Triggers as soon as key is press)
  • Second Keypress Event occurs (Triggers when key character is typed)
  • Third Keyup Event occurs (Triggers when key is up, after it is been pressed)

Example 1 - Keydown Event: We will show alert in all situation whenever user press any key in textbox. (Live Demo)

I have a html input control, whose id is "txtInput" on writing any character inside textbox it should display alert.


<b>Type anything in below textbox to trigger, keydown event</b><br />
<input id="txtInput" type="text" />

JQuery script for showing alert on keydown event


<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#txtInput").keydown(
            function (event) {


                if (event.keyCode == 13) {
                    alert("You have pressed enter");
                }
                else if (event.keyCode == 18) {
                    alert("You have pressed Alt key");
                }
                else if (event.keyCode == 32) {
                    alert("You have pressed Spacebar key");
                }
                else if (event.keyCode == 27) {
                    alert("You have pressed Escape key");
                }
                else if (event.keyCode >= 48 && event.keyCode <= 57) {
                    alert("You have pressed numeric key");
                }
                else if ((event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode >= 97 && event.keyCode <= 122)) {
                    alert("You have pressed alphabet key");
                }                
                else {
                    alert("You have pressed: " + event.keyCode);
                }


            }
        );


    });
</script>


Example 2 - Keypress Event: We will show alert in all situation whenever user press any key in textbox. (Live Demo)

In above example you might have notice problem with event.keyCode, it triggers as soon as we press the key.  That is we cannot used this event when we want to check combination of key (Example: shift + 2 .i.e. "@" symbol is pressed or not)  For such situation were we want to identify which character is pressed, it is good to use event.which event.  Let understand that with example

I have a html input control, whose id is "txtInput" on writing any character inside textbox it should display alert.


<b>Type anything in below textbox to trigger, keydown event</b><br />
<input id="txtInput" type="text" />

JQuery script for showing alert on keypress event


<script language="javascript" type="text/javascript">
    $(document).ready(function () {



        $("#txtInput").keypress(
            function (event) {


                if (event.which == 64) {
                    alert("You have pressed @ sign");
                }
                else if (event.which == 35) {
                    alert("You have pressed # sign");
                }
                else if (event.which == 36) {
                    alert("You have pressed $ sign");
                }
                else if (event.which == 42) {
                    alert("You have pressed * sign");
                }
                else if (event.which >= 65 && event.which <= 90) {
                    alert("You have pressed uppercase alphabet character");
                }
                else if (event.which >= 97 && event.which <= 122) {
                    alert("You have pressed lowercase alphabet character");
                }
            }
        );



    });
</script>



Example 3 - Keyup Event: We will show alert in all situation whenever user press any key in textbox. (Live Demo)

I have a html input control, whose id is "txtInput", when user releases key on keyboard this event will trigger and it should display alert.


<b>Type anything in below textbox to trigger, keydown event</b><br />
<input id="txtInput" type="text" />

JQuery script for showing alert on keyup event


<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#txtInput").keyup(
            function (event) {


                if (event.keyCode == 13) {
                    alert("You have pressed enter");
                }
                else if (event.keyCode == 18) {
                    alert("You have pressed Alt key");
                }
                else if (event.keyCode == 32) {
                    alert("You have pressed Spacebar key");
                }
                else if (event.keyCode == 27) {
                    alert("You have pressed Escape key");
                }
                else if (event.keyCode >= 48 && event.keyCode <= 57) {
                    alert("You have pressed numeric key");
                }
                else if ((event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode >= 97 && event.keyCode <= 122)) {
                    alert("You have pressed alphabet key");
                }                
                else {
                    alert("You have pressed: " + event.keyCode);
                }


            }
        );


    });
</script>

I will be discussing more JQuery examples in JQuery example series.

Monday, September 26, 2011

JQuery Double Click Event

In this article we will learn how JQuery double click events work

Example 1: Show Alert on double click of paragraph, using JQuery Event (Live Demo)
I have a simple html para, whose id is "MyPara" on double click of this paragraph it should display alert.

<p id="MyPara" style="background-color:Yellow;color:Red;font-size:2.2em;">
Double Click, Paragraph to display alert
</p>

JQuery script for showing alert on double click of paragraph

<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#MyPara").dblclick(
            function () {
                ShowAlert();
            }
        );


    });


    function ShowAlert() {
        alert("Alert message on double click");
    }
</script>



Double click event is almost similar to click event, here instead of click we have used dblclick.

I will be discussing more JQuery examples in JQuery example series.

Sunday, September 25, 2011

JQuery Click Event

In this article we will learn how JQuery click events work

Example 1: Show Alert on html button click using JQuery Event (Live Demo)
I have a simple html button control, whose id is "btnClickMe" on click of this button we will display alert.
<button id="btnClickMe">Click Me to Display Alert</button>

JQuery script for showing alert on button click
<script language="javascript" type="text/javascript">
    $(document).ready(function () {


        $("#btnClickMe").click(
            function () {
                ShowAlert();
            }            
        );


    });


    function ShowAlert() {
        alert("Alert message on click");        
    }
</script>

Explanation of how things are working here

Step 1: Defining document.ready function.
    $(document).ready(function () {

    });
Whenever we are putting our JQuery code inside this code block means, we are instruction browser to execute JQuery code only when page is loaded and it is ready to execute JQuery code.

Question: Can i put JQuery code directly without even putting it in document.ready function.
Answer: Yes you can do, but in that case you need to be sure that your control is loaded before your JQuery code tries to access it, otherwise you may receive error.

Step 2: Create a Alert function which can be called on button click event.
Note: This is a simple alert function, which is a common javascript alert function.

    function ShowAlert() {
        alert("Alert message on click");      
    }

Step 3: Write button click event to call alert
        $("#btnClickMe").click(
            function () {
                ShowAlert();
            }            
        );
Please note here #btnClickMe is button id on whose click event we are going to show alert.
Watch Live Demo



Example 2: Show Alert on asp.net button click using JQuery Event
I have a asp.net button control, whose id is "btnClickMe" on click of this button we will display alert.

<asp:Button ID="btnClickMe" runat="server" Text="Click Me" />


JQuery script for showing alert on asp.net button click<script language="javascript" type="text/javascript">
    $(document).ready(function () {

        $("#<%=btnClickMe.ClientID%>").click(
            function () {
                ShowAlert();
            }            
        );

    });

    function ShowAlert() {
        alert("Alert message on click");      
    }
</script>



I will be discussing more JQuery examples in JQuery example series.

Saturday, September 24, 2011

Attribute Selector examples in JQuery

With attribute selector in JQuery we can select element based on particular attribute.

Lets understand attribute selector by example.

My HTML looks something as below image.




And it appears in browser as under



Now let see, how attribute selector works in JQuery.

Example 1: Has Attribute Selector (Live Demo)
Let change all the link appearing in blue to red.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("a[href]").css("color", "Red");        
    });

</script>


It will result in following output on browser screen.



Example 2: Equal to Attribute Selector (Live Demo)
Let change all the link appearing in blue to red only for links which as rel="nofollow"

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {

       $("a[rel='nofollow']").css("color", "Red");        
    });

</script>

It will result in following output on browser screen.


Example 3: Start with Attribute Selector (Live Demo)
Let change all the email link appearing in blue to red.  i.e. Change all links which are begining with mailto

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("a[href^='mailto']").css("color", "Red");        
    });

</script>

It will result in following output on browser screen.


Example 4: Ends with Attribute Selector (Live Demo)
Let change all the link appearing in blue to red for one which are ending with .com.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("a[href$='.com']").css("color", "Red");        
    });

</script>

It will result in following output on browser screen.


Example 5: Contains Attribute Selector (Live Demo)
Let change all the link appearing in blue to red for one which contains word example.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("a[href*='example']").css("color", "Red");        
    });

</script>

Note: Here we are selecting href attribute with word example, hence their are 3 links pointing to http://www.Syntax-Example.com, it has shown all three links in red color.

It will result in following output on browser screen.



Example 6: Not Equal to Attribute Selector (Live Demo)
Let change all the link appearing in blue to red for one which NOT contains rel="nofollow". 
Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("a[rel!='nofollow']").css("color", "Red");        
    });

</script>

It will result in following output on browser screen.


JQuery Selector Basics and understanding Tag Selector

What is JQuery Selectors?
JQuery selectors are used to select elements.  In order to apply any effect or style change, it is necessary to select element, JQuery Selectors are used to select element in order to apply those changes.

Lets understand through different examples.

I have a form with  text formatted with following html tags

  • H2 Tag
  • HR Rule Tag
  • P Paragraph Tag
  • UL/LI Tag
  • B bold Tag
My HTML looks something as below image.

And it appears in browser as under

Ok, now we will start with basic examples of how selectors works in JQuery.

Select Particular Tag and apply CSS Format

Example 1: Let select all paragraph tag in our page and change its text background to yellow color.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
    $("p").css("background-color", "Yellow");
});
</script>


It will result in following output on browser screen.


Example 2: Let select all "h2" tag (header tag on top) in our page and change its font family and size to verdana, 35px.

Please add below script at the end of the page.
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("p").css("background-color", "Yellow");
        $("h2").css("font-family", "Verdana");
        $("h2").css("font-size", "35px");
});
</script>

It will change all h2 tag font.  You can notice that one of h2 lies in Nested master page, while other is on page where JQuery selector tag is defined.

Well obvious questions might be running in your mind that i can do all this from CSS file, than what is the advantage?
The only thing I can say at this point is hold on for a while and we will discuss how it is different and more beneficial.

In next few blog post we will understand few more ways to use JQuery selectors.

ID Selector examples in JQuery

In this post we will understand more about ID Selector in JQuery.  That is selecting a particular element based on his unique ID.

Continue with our earlier example of JQuery Selector

I have following data input screen


Syntax

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("#ElementID").css("stylename", "stylevalue");
    });
</script>



Example 1: Lets give border color to blue to location textbox control on our asp.net web form.
Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("#<%=txtLocation.ClientID%>").css("border-color", "blue");
    });
</script>

Whenever we are selecting asp.net control, it renders html id as something like
MainContent_ContentPane_txtLocation

JQuery needs unique client id, in order to apply css effect.

Since my asp.net webform is using Master page + Nested master page + Control ID
So here: MainContent_ContentPane_txtLocation
MainContent is MasterPage ID
ContentPane is Nexted MasterPage ID
txtLocation is Control ID


Please note:  I have used #<%=txtLocation.ClientID%>
# - Is to tell we are applying css based on ID.
<%=txtLocation.ClientID%> - is used to get client id of txtLocation control.


Note: If you try something like
       $("#txtLocation").css("border-color", "blue");
It won't apply any border to txtLocation, because JQuery will not be able to find txtLocation to apply CSS.


It will result in following output on browser screen.

Example 2: Lets apply yellow background color to table containing all input controls.
My table is not asp.net server control, i.e. it doesn't have runat="server"
Its html looks like <table id="tblInputForm">

Remember if control you are trying to select is not asp.net server control (i.e. not having runat="server"), then you will be able to select it directly.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("#<%=txtLocation.ClientID%>").css("border-color", "blue");
       $("#tblInputForm").css("background-color", "yellow");
    });
</script>

It will result in following output on browser screen.

Tag or Element Selector examples in JQuery

In this post we will understand more about Tag or Element Selector in JQuery.

Continue with our earlier example of JQuery Selector


I have created a sample asp.net web form.
My HTML looks something as below image.
And it appears in browser as under

Now let see, how element selector works with asp.net controls in JQuery.


*Please Note: Asp.net web form which is used for example is not following all best practices, since this tutorial series will be focusing only on Jquery.  It doesn't contains code in .cs file for input real data in DB.

We know that internally when asp.net web page renders,

  • All label controls as span tag 
  • All Textbox control as input tag
  • All dropdown control as select tag
    • All dropdown items as option element
  • And so on... ok, now lets begin the game!


Example 1: Lets highlight all label controls, with yellow background.
Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("span").css("background-color", "Yellow");
    });
</script>

It will result in following output on browser screen.


Example 2: Lets give border to all textbox controls, with blue border.
Please add below script at the end of the page.


<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("span").css("background-color", "Yellow");
        $("input:text").css("border-color", "blue");        
    });
</script>


Please note: input element is used for multiple purpose,
<input type="text"/> - will display textbox
<input type="submit"/> - will display button

You might have also notice that multiline textbox is rendered as textarea and that is reason it doesn't have blue border.

Output on browser screen.

We have found that here it is an issue since, we want to give blue border to all textbox, irrespective of whether it is textmode is multiline (i.e. Textarea) or normal single line textbox control (i.e. Input type="text").

I can add one more line for Textarea to achieve this, but it will not be good way to do things from maintainability point of view.  Example: let say if requirement gets change and i want my blue border to appear as red.  There are chances that i update one line and not other, in that case few textbox have blue border and other have red.

Watch Live demo of JQuery Element Selector Example

Multiple Selector examples in JQuery

In this post we will understand more about Multiple Selector in JQuery.

Continue with our earlier example of JQuery Selector.  In my previous post, We have found that their is an issue since, we want to give blue border to all textbox, irrespective of whether it is Textarea (i.e. textbox with textmode is multiline) or normal singleline textbox control (i.e. Input type="text").


As i said, I can add one more line for Textarea to achieve this, but it will not be good way to do things from maintainability point of view.  Example: let say if requirement gets change and i want my blue border to appear as red.  There are chances that i update one line and not other, in that case few textbox have blue border and other have red.

This can solve problem, but their is a better way to solve problem.
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("span").css("background-color", "Yellow");
        $("input:text").css("border-color", "blue");        
        $("textarea").css("border-color", "blue");        
    });
</script>

Instead of writing two lines of code, we can take advantage of Multiple Selector where we can pass multiple selectors to apply same style.

so you just need to change your JQuery code to something like one i wrote below.
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("span").css("background-color", "Yellow");
        $("textarea, input:text").css("border-color", "blue");        
    });
</script>

Output on browser screen

We will be looking for more Multiple selector example as we walk through this tutorial

Watch Live demo of JQuery Multiple Selector Example

CSS Class Selector examples in JQuery

In this post we will understand more about CSS Class Selector in JQuery.  CSS Class selector is selecting CSS Class in JQuery.

Continue with our earlier example of JQuery Selector

This time, i have defined two css classes in css style file for paragraph tag. i.e. para1 and para2.  This two css class have few font family and size change.

My HTML looks something as below image.

And it appears in browser as under

Now let see, how class selector works in JQuery.

Example 1: Let select paragraph tag with css class as "para1" in our page and change its text background to yellow color.  Also select paragraph tag with css class as "para2" in our page and change its text background to lime color.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $(".para1").css("background-color", "Yellow");
        $(".para2").css("background-color", "lime");
    });
</script>

It will result in following output on browser screen.


Please note, that class selector should always start with "." (dot).  Selector will not be able to select class element if defined without "."

Example:  Incorrect way of declaration - Class element without "." (dot)
<script language="javascript" type="text/javascript">
    $(document).ready(function () {

        $("para1").css("background-color", "Yellow");
        $("para2").css("background-color", "lime");

    });
</script>


Example:  Correct way of declaration - Class element with "." (dot)
<script language="javascript" type="text/javascript">
    $(document).ready(function () {

        $(".para1").css("background-color", "Yellow");
        $(".para2").css("background-color", "lime");

    });
</script>



Example 2: To be more specific in above example that only paragraph tag which has class name as para1, should only assign background color as yellow, you should explicitly mention "p.para1" rather than ".para1"  

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("p.para1").css("background-color", "Yellow");
    });
</script>

It will result in following output on browser screen.

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape