- 4 years ago
- Zaid Bin Khalid
- 6,229 Views
-
3
In this session, you will learn how to write the jQuery code with the help of an example.
Standard jQuery Syntax
A jQuery statement started with the ($) dollar sign and ends with a (;) semicolon sign in JavaScript.
In jQuery, the sign of ($) dollar is just an alias for jQuery. Let us suppose the mention below example will demonstrate the most basic statement of the jQuery code.
<script>
$(document).ready(function(){
// Some code to be executed...
alert("Hello World!");
});
</script>
“Hello World!” alert message will display to the user in the above example.
Explanation of code
If you are a beginner in the jQuery, you will think at some point during working what that code was all about. Let’s learn some of the parts of this script one by one
- The <script> element is a JavaScript library, the code can be placed inside the <script> element. In case during work, if you want to place it in an external JavaScript file, you just remove this part which is preferred.
- The $(document).ready(handler) statement also called as ready event. Where the handler is a function that is passed to the ready( ) method to be executed safely as soon as the document is ready to be manipulated as shown in an example in shorthand notation as mention below:
<script>
$(function(){
// Some code to be executed...
alert("Hello World!");
});
</script>
Now let’s assume another example that set the text paragraph after DOM is ready to use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Document Ready Demo</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$("p").text("Hello World!");
});
</script>
</head>
<body>
<p>Not loaded yet.</p>
</body>
</html>
In the above example paragraph text is replaced automatically when the document is ready. Let’s assume the one last example in case if the user wants to perform some action before execute the jQuery code to replace the paragraph text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Click Handler Demo</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("Hello World!");
});
});
</script>
</head>
<body>
<p>Not loaded yet.</p>
<button type="button">Replace Text</button>
</body>
</html>
In the above example, you can see the paragraph text is replaced only when “Replace Text” <button> occur. When a user clicks this button it will replace text into paragraph text form.
Note: The jQuery code should place inside the document ready so your code will execute/work accordingly when the document is ready.
- 4 years ago
- Zaid Bin Khalid
- 6,229 Views
-
3