Creating custom events for a control in HTML

Hi All,

Sometimes we need to create a custom event for a control which we can use it to get the context of the control.Below is a quick method using jQuery to do that.

In the below example i have created an init method for input tag.

This method can be simply trigger using  
$(<SELECTOR>).trigger("<METHODNAME>")


Example



 <input id="txtName" class="news" init="initializeSection1" />

    <input id="txtName" class="news" init="initializeSection2" />

    <script>
        $(document).ready(function () {

            $(".news").bind("init", function (e, data, val) {
                var initializeFunctionName = $(this).attr("init");
                window[initializeFunctionName](e, data, val);
            });

            $(".news").trigger("init");

        });

        function initializeSection1(e, data, val) {

            alert("I called initializeSection1");
            var parentObj = $(e.currentTarget).parent()
        }


        function initializeSection2(e, data, val) {

            alert("I called initializeSection2");
            var parentObj = $(e.currentTarget).parent()
        }

    </script>

Comments

Popular posts from this blog

Install Node.js without admin rights

Create a lean React Solution using Typescript

Replace all occurence of String in JavaScript