Sunday, October 6, 2013

Verify whether HTML object has the event using javascript or jQuery

We would be using multiple events or plugins to get our requirement done using jQuery.

While adding them we may not know whether the plugin is activated or not that gives error to the browser if it does not initiate and stops the next line of scripts in jQuery which we should not be doing. 

To get rid of this, we can use jQuery hasOwnProperty which tells whether the HTML object has the event which we are checking for.

Below is the sample code:

Consider we have included the CKEDITOR in the script and it applies for the textareas.


<html>
<head>
<script type="text/javascript" src="ckeditor.js">
<title>Test Object Event Existence</title>
</head>
<body>
<ul>
     <li>First name: <input type="text" name="fname" /> </li>
     <li>Last name: <input type="text" name="lname" /> </li>
     <li>Address: <textarea name="address" id="address" ></textarea></li>
</ul>
</body>
</html>
For the above script, to check whether the textareas has CKEDITOR or not we can check as below

$('#address').hasOwnProperty('CKEDITOR') 

If it exists it returns true else returns false.


No comments: