Variables and Javascript Methods In jQuery


In this video tutorial we shall see how to use variables and javascript methods in jQuery.

In this tutorial, we shall take a image inside our html document. Once the user clicks on this image, we shall use some javascript methods to generate random discounts and display it using alert box.

Note:
var is a keyword to declare variable.
Math.random() generates random numbers between 0 and 1.
Math.floor() is used to round off the floating point number to integer.
alert() is used to show the message stored in the variable in alert box.
+ is concatenation operator.

HTML code
index.html

1
2
3
4
5
6
7
8
9
<html>
 <head><title>Variables and JavaScript Methods: jQuery</title></head>
 <body>
                      <img src="images/aperture.png" width="79" height="79" />
 
   <script type="text/javascript" src="script/jquery-1.8.1.min.js"></script>
   <script type="text/javascript" src="script/my_script.js"></script>
 </body>
</html>

Here we are including 1 image.
We have also linked the web page to jQuery library file and our my_script.js file.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
 $(document).ready( function() {
 
   $("img").click( function() {
 
     var discount = Math.floor( Math.random() * 5 ) + 10;
     var msg      = "Discount: "+discount+"%";
     alert(msg);
 
   });
 
 });

Once the web page is loaded, and the user clicks on the image:
Math.random() function generates some random number between 0 and 1, which is multiplied by 5 and the resulting number is then rounded off to a integer number using Math.floor() method.
This number is then added with some string message and is stored inside another variable called msg.
This is passed to alert() method and is displayed on a alert box.

Math.random() and Math.floor() and alert() are javascript functions.

Video Tutorial: Variables and Javascript Methods In jQuery


[youtube https://www.youtube.com/watch?v=IfGmVi3ZuVw]

YouTube Link: https://www.youtube.com/watch?v=IfGmVi3ZuVw [Watch the Video In Full Screen.]



If you want to learn “javascript” visit Javascript Category on our blog.

With this tutorial, you now know that, your javascript knowledge will come handy. If you don’t know Javascript, still you need not worry as we would explain the things we will use in our jQuery tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *