In this tutorial we will be using JQuery to show and hide images that are displayed in our web page. If you would like to use the files used in this tutorial you can click here to download them.
When using JQuery the first thing that is required is for us to link to the JQuery library. The link to this library is contained within the header tags of the web page and look like this:
1 2 3 | <head> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> |
The next part of this code that is required is for us to create the functions that the buttons will link to. When the user presses one of these buttons the image will go into that state unless already in that state. It does this by using an “on click” that linking to the javascript function.
1 2 3 4 5 6 7 8 | <script> function showImage(){ $('#imgSwitch').show(); } function hideImage(){ $('#imgSwitch').hide(); } </script> |
Now we need to create the img tags and give the image an ID that will work with the functions we have just created. The code for this looks like so:
1 | <img id="imgSwitch" src="cjdesign.png"> |
The final part of code that is required is the form that links to the functions we created in the second group of javascript code. For this section of code we will be creating two buttons that will allow the change in image.
1 2 3 4 | <form> <input type="button" value="show" onclick="showImage()"></input> <input type="button" value="hide" onclick="hideImage()"></input> </form> |
And finally this is what all of the code looks like together. The code you have created should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <head> <title>Show and Hide Images</title> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> function showImage(){ $('#imgSwitch').show(); } function hideImage(){ $('#imgSwitch').hide(); } </script> </head> <body> <h1>Showing and Hiding Images</h1> <p>This is an example of showing and hiding images.</p> <img id="imgSwitch" src="cjdesign.png"> <form> <input type="button" value="show" onclick="showImage()"></input> <input type="button" value="hide" onclick="hideImage()"></input> </form> </body> </html> |
Related posts: