jQuery Hover Effect
Creating a Hover Effect Using jQuery:
In this section we will show the code to use to create a simple hover effect. We will use two different pictures and we will have one picture change to another picture when the mouse hovers over the picture box.
First we will need to call our jQuery in the HTML and indicate that our script will be JavaScript. Our code will lokk something like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
The next thing we will need to do is to create the jQuery code that will be used to manipulate the images and the effect on them. Our code to accomplish that task will look something like this. I have added line number to explain the code more easily. When usinge the actual code you would not write the line numbers. If you do, the code will not work properly. The following section of code must go immediately after the code that was already enterd in the previous example box:
1) $(document).ready(function() {
2) $('img.swap').hover(
3) function() {
4) $(this).attr('src', "Margarita1.jpg");
5) },
6) function() {
7) $(this).attr('src', "DSC_0511_large.jpg");
8) });
9) });
10) </script>
In line 1 we are making sure the webpage (or the 'document') is ready and then is able to begin a jQuery function
In line 2 we are giving a condition. We are saying that when an image (img) that is in a class called "swap" (.swap) is hoverd over with the mouse (.hover) then we are to execute a function (or functions).
In line 3 we call a function that will identify our first conditional.
in line 4 we are saying that "this" div has an attribute (.attr). This arrtibute is thatit contains a "source" ('src') which is an image that is called "Margarita1.jpg".
Line 5 ends the function.
Line 6 calls a second fiction which will identify another condition.
Line 7, like the previous function, says that "this" div has an attribute (.attr) which contains a source ('src') which is another picture called "DSC_0511_large.jpg".
Lines 8 and 9 close up the functions and the condition statements. If these sections are not closed properly, the JavaScript and/or jQuery will not work properly.
Line 10 closes the entire Script section which began in the previous example box.