Thursday, January 12, 2012

Changing Page Content with JQuery

This tutorial is in response to a specific request by someone. Here is the summarized version of their request:

How would you use JQuery to create an image that changes when the mouse is over it and also changes the content (text/image(s)) in a different section of the page dynamically (without refreshing the page)?

In order to change page content with JQuery, you must first import JQuery and know the basics of how to use it, all of which I discussed here.


We will also need two images to test this out with and a section of content to change dynamically when the mouse moves over and out of this image. Here is the code we will use for our initial image:

<body>

<img id="hoverImage" src="http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin1.png"/>

</body>


Notice that I added the "id" attribute to the image above, and I set its value to "hoverImage". ID's are used to identify individual elements of the page to apply additional CSS styling or JavaScript/JQuery coding to.

I am using this penguin image as the default:










The other image will be coded in later using JQuery.


Next is the code that will be used for the section of content that will dynamically change (for simplicity we will use just text here, but you can also add images and such if you want):

<body>

<img id="hoverImage" src="http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin1.png"/>

<div id="changeContent">

This is the section of content to change, with an id of "changeContent".

</div>

</body>


Notice how I used a div element (which is used primarily for containing other elements and content), and I gave that div an ID of "changeContent". Now we have two different elements that we will be able to access in JQuery: the image and the content section.


Finally, now that our HTML code is ready, we can insert the JQuery scripting. I'll start where we left off in the last tutorial on using JQuery:

<head>
 
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
 
<script type="text/javascript">
 
    $(document).ready(function()
    {
        alert("JQuery is working! :D");
    });
 
</script>
 
</head>


Instead of displaying a JavaScript alert box, we want to capture the events that are generated when the mouse enters and leaves the dimensions of the image. This is relatively simple to do:

<head>
 
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
 
<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#hoverImage").mouseenter(function()
        {
            
        }).mouseleave(function()
        {
            
        });
    });
 
</script>
 
</head>


There are 3 things to point out in the above code:
  1. Similar to the "$(document).ready()" command that we are still using because it executes JQuery code when the page has loaded,

    $("#hoverImage").mouseenter()

    and

    $("#hoverImage").mouseleave()

    are used to execute code when the mouse enters and leaves our image with the "hoverImage" ID.

  2. The penguin image with an ID of "hoverImage" is being referenced through the use of the pound symbol like so:

    $("#hoverImage")

    This can be used to access any HTML element on the page through the same syntax:

    $("#IDHere")

  3. "mouseenter()" and "mouseleave()" are chained together. It could have also been coded like this:

    <head>
     
    <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
     
    <script type="text/javascript">
     
        $(document).ready(function()
        {
            $("#hoverImage").mouseenter(function()
            {
                
            });
            
            $("#hoverImage").mouseleave(function()
            {
                
            });
        });
     
    </script>
     
    </head>
    
    
    Make sure to remember that either way you do it, the function:

    function() { }

    must be contained within a set of parentheses from the event, e.g.:

    mouseenter(function() { });

    and

    mouseleave(function() { });


Now that you understand how the events and their anonymous functions work, I'll show you how to change the picture (with ID of "hoverImage") and the content (with ID of "changeContent") when the mouse leaves and enters the image. It can be done with the following code:

<head>
 
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
 
<script type="text/javascript">
 
    $(document).ready(function()
    {
        $("#hoverImage").mouseenter(function()
        {
            $("#hoverImage").attr("src", "http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin2.png");
            $("#changeContent").html("Your mouse has entered the image.");
        }).mouseleave(function()
        {
            $("#hoverImage").attr("src", "http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin1.png");
            $("#changeContent").html("Your mouse has left the image.");
        });
    });
 
</script>
 
</head>


Just like I previously used:

$("#hoverImage").mouseenter

and

$("#hoverImage").mouseleave

I then used the same technique to call the "attr" and "html" functions. The "attr" function is for changing HTML attributes - in this case, I changed the "src" attribute (the image's source) so that the same image element was used but with a different image URL as its source.

Penguin 2 (the non-default image) is displayed when the mouse enters the bounding box of the image by changing the "src" attribute:

$("#hoverImage").attr("src", "http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin2.png");

and likewise, Penguin 1 (the default image) is displayed again (like before) when the mouse enters the bounding box of the image by changing the "src" attribute:

$("#hoverImage").attr("src", "http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin1.png");

Similarly, the contents of the "changeContent" div section of the page are changed using the "html" function:

$("#changeContent").html("Your mouse has entered the image.");

The "html" function changes the contents inside the opening and closing tags of the chosen element. Here's what it originally starts out as:

<div id="changeContent">

This is the section of content to change, with an id of "changeContent".

</div>


and then the content changes dynamically when the mouse enters and leaves the image:

<div id="changeContent">

Your mouse has entered the image.

</div>




Here is a live demo using all of the code entered above that you are welcome to try out:

http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/demo.html

Two things to note before I finish:
  1. If you go to the demo above and the contents of the image and content div are changed, and then you click View > Source (or a similar button to that) in your browser, the original HTML code will be displayed to you. In other words, the browser does not keep track of any dynamically modified content, other than for what goes on in the page itself. There are plugins and such (the Firebug plugin for Firefox is well known for this) to view HTML content and other aspects of the page live.
  2. I added one little piece of extra code to my demo. It's a little CSS styling I applied to the HTML image element (at the end):

    <img id="hoverImage" src="http://www.thecodingwebsite.com/tutorials/demos/changingpagecontent/penguin1.png" style="border:1px solid black;"/>

    It adds a 1 pixel thick (very thin) black border around the image so you can see its bounding box for the demo.


By the way, here are some JQuery API documentation links for further reading about mouse events (there are many other types of events, listed on this website, including mouse move, keyboard key press, and button click events for example):

Mouse events:http://api.jquery.com/category/events/mouse-events/
Mouseenter: http://api.jquery.com/mouseenter/
Mouseleave: http://api.jquery.com/mouseleave/

Events: http://api.jquery.com/category/events/


Now you know how to capture mouseenter and mouseleave events, as well as being able to use other JQuery events that you research on your own in the future. You can make some very interesting web pages with JQuery using the techniques I have shown you here, so enjoy! :]

7 comments:

  1. You are a gifted teacher! I don't know JavaScript very well yet, but I was able to follow everything thanks to your patient, step-by-step style.

    Just one note: Don't you mean "anonymous function" rather than "unanimous function"?

    ReplyDelete
    Replies
    1. Thank you!

      Oop. Yes, I did! I fixed it now.

      Thanks.

      - Andrew

      Delete
  2. This is great! Nice breakdown of the information, especially for someone like me new to jQuery.

    Question though: How do you add more content?? You don't have to type everything into the jQuery section ("Your mouse has entered the image."); do you??

    I'm trying to create a bio section of about 7-8 people. Where you click on their name and their photo appears along with a short bio. This seems like a step in the right direction for me, just need a little more help

    ReplyDelete
    Replies
    1. Thanks!

      I believe you have 4 options:

      1. Put that content on a separate page and use frames. This is not a good option to take, and it doesn't suit your needs very well either.

      2. Create all of the HTML and CSS content as if everything were showing at once. Then, hide the HTML container of each section using JS/JQ (or you could use HTML - that might be better since the HTML will load first). Lastly, show/hide the content when clicked. This is probably what you would want. Here are some links that will help greatly:

      http://www.w3schools.com/jquery/jquery_hide_show.asp
      http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_show
      http://www.w3schools.com/css/css_display_visibility.asp

      3. (If you don't understand half of the things in this, that's okay. ;) ) If you have the bio information and such stored in e.g. a database or file somewhere (not as HTML but as text and URL's and etc.), you could create a PHP page that doesn't do anything except generate the requested section (using GET, outputting HTML code). Then, using Ajax (another JS extension), you could call that PHP script and load in the result all on the same page. This is a nice option since it removes the need to create redundant HTML, but it's more difficult to do. If you want to go over the top you could store the generated HTML in an array in JS in case the viewer hides and shows multiple sections (to avoid the need to request the PHP script multiple times for the same info).

      4. You could also do what you were dreading to do when making your post: output the data using JS/JQ code. There are actually two ways to do this though. One way is what you wouldn't like: have redundant code that manually outputs each section. The other way is actually another nice option for you to take: store the information in an array (or load it in from a file on the server using the JQ "get" function) and then simply use that. More info on JQ "get":

      http://api.jquery.com/jquery.get/
      http://stackoverflow.com/questions/1981815/jquery-read-a-text-file

      The information I presented here, oddly enough, is still kind of vague. It will get you going in the right direction though.

      - Andrew

      Delete
    2. Wow man, super quick response! I appreciate all of the possible solutions!!

      I'm going to look into the solutions for #2. Number 3 & 4 are a bit over my head... I've never done anything with PHP pages and I think i've seen AJAX in some of the forums i've been on but I def don't know how to implement it. Most of the JS/JQ I use is from sites like yours and Overstack where it's more trial and error for me...

      Talking to someone like you makes me feel like I know nothing! haha But I'm trying and learning more and more as I go... My cousin is going to help me out with some of the functionality too. I'm going to show him your response, #3 & #4 will make much more sense to him and he can give me the watered down version.

      I have all of the HTML & CSS constructed already, everything is just on my local drives at the moment. Waiting until I receive the rest of the content from the client to make everything live. I'm going to check out those links later today and I'll let you know how I make out.

      Thanks again man!
      Cory

      Delete
  3. Thnx a lot man.....Awesome work you have done here

    ReplyDelete