Are you looking for my non-technical blog?

This is now my technical-only blog, my non-technical blog is here.

29 December 2011

Quick jQuery Intro.

For the second time in two days, one of my friends asks me about jQuery. So, here is a quick introduction to it.Let's say we have the following HTML that contains a list of four items
<html>
<head>
<title>jQuery demo</title>
</head>
<body>
<ul>
<li class="news_line">Mr. One</li>
<li class="news_line">Mr. Two</li>
<li class="news_line">Mr. Three</li>
<li class="news_line">Mr. Four</li>
<ul>
</body>
</html>
Now we want to make it more interactive, so when the mouse hovers on any of the below items it turns red, and when it goes away it turns white again. Here comes the beauty of jQuery, you can give them all a CSS class "news_line", hence you write a function once and it is applicable to them all. So, first of all, you have to include the following script.

<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
></script>
You put all your jQuery script between the following, this makes sure it's not executed until the page is loaded successfully
<script>
$(document).ready(function(){
... YOUR jQUERY SCRIPT HERE ...
});
</script>
We now are going to use the following function, which simply mean attach an event catcher to the items with class "news_line", and make the event trigger is 'mouseover', i.e. whenever the mouse hovers over it. We also have other events such as 'mouseout', etc.
$(".news_line").live('mouseover',function(){
... DO SOME STUFF HERE ...
});
One more thing to notice is "$(this)", the above command searches for all items with class "news_line", now when we use "$(this)", we are referring the the item we are dealing with now. And starting from that point we use another functions "css()" to change the object's background colour. You may in some other cases use stuff like "$(this).children().css()" to change the colour of all of the children of the matched items, or "$(this).parent().parent().hide();" to hide the parent of the parent of the item you are referring to, etc.So, finally here is the code we are talking about here.
<html>
<head>
<title>jQuery demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".news_line").live('mouseover',function(){
$(this).css("background-color","#ff0000");
});
$(".news_line").live('mouseout',function(){
$(this).css("background-color","#ffffff");
});
});
</script>
</head>
<body>
<ul>
<li class="news_line">Mr. One</li>
<li class="news_line">Mr. Two</li>
<li class="news_line">Mr. Three</li>
<li class="news_line">Mr. Four</li>
<ul>
</body>
</html>

Finally, here is a list of all jQuery functions, events, etc.
http://visualjquery.com/

1 comment:

  1. I am thinking that in this time you should give a try to this new app Car Crusher Mod Apk : which is now most trending app in the world.

    ReplyDelete