How to execute jQuery code? [Example]

Leave a Comment

There are two ways you may want to execute jQuery codes.

Ways #1. As and when page loads, execute the jQuery code
<script language="javascript" type="text/javascript">
$(function () {
$("#div1").css("border", "2px solid green");
});
</script> 

OR
<script language="javascript" type="text/javascript">
$("#div1").css("border", "2px solid green");
</script> 

The benefit of executing jQuery code in this way is that it doesn‟t wait the whole page to load completely, so in case you want user to see the effects as soon as the corresponding elements are loaded, you can use this.

However the disadvantage is that if the element on which jQuery has to execute has not loaded then it will error out or you will not get desired result; so while using this way of executing jQuery code, you will have to make sure that the element on which you want to work with jQuery is loaded first (you can place your jQuery code right after your HTML element).

Ways #2. Execute jQuery only when the complete DOM objects (the complete page has been loaded). You will have to wrap your code in .ready function.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#div1").css("border", "2px solid green");
});
</script> 

This is the better and safer way to execute jQuery. This makes sure that jQuery code will execute only if complete page has been loaded in the browser so you are rest assured that user will not see any undesired behavior on the page.

As a developer, the decision of where and how to write jQuery code lies on you. I prefer to use 2nd method as it ensures that my complete page is loaded in the browser and I am ready to play with any element available on the page.

0 comments:

Post a Comment