Press enter to skip the top menu

JavaScript

Fading Images

Learning Outcomes

On completion of this lesson you will know how to interactively increase or decrease the opacity of an image.

Go to top

Introduction

This page is a short and easy roundup of our exploration of JavaScript. The viewer is simply presented with an image and two buttons: one to increase the brightness of the image and another to reduce it to invisibility or zero opacity.

Although the three components of a web page, i.e. HTML, CSS and JavaScript were short enough in this case to be put into a single file, we still adhered to our custom of keeping them all separate from each other, thus give very short code listings.

Go to top

Opacity

Before examining our code we shall first give a short explanation of what exactly we mean by 'Opacity' as far as images are concerned. An image shown in full colour has an opacity of 1 while an image that is totally transparent has an opacity of zero.

Two versions of an image in full opacity and zero opacity
Fig 1: The top image has an opacity value of 1 while the lower image has an opacity of 0.3

Our code examples in this page will result in a web page where we can use two buttons to vary the opacity of an image between 1 and zero.

Listing 1
                        .buttonSytle{
                            width:90px;
                            display:inline;
                        }
                        .otherDivStyle{
                            display:block;
                            width:250px;
                            margin-left:auto;
                            margin-right:auto;
                        }
                        .mainDivStyle{
                            background-color:#444;
                            display:block;
                            padding-bottom:40px
                        }
                        .imageStyle{
                            display:block;
                            margin:40px auto 20px auto;
                            width:40%;
                        }
                        h1{
                            text-align: center;
                            color: beige;
                        }
                    

The above CSS code lays out our very simple page.

For the main <div> it creates a dark grey background. For the second <div> it centers it and gives it a width of 250 pixels.

For the image it centers it and assigns a width of 40% of its container.

Listing 2
                        <!DOCTYPE html >
                        <html lang="en">
                            <head>
                               <title>Opacity Test</title>
                                <link href="Fading%20Images.css" rel="stylesheet" type="text/css">
                                <script src="Fading%20Images.js" type="text/javascript"></script>
                            </head>
                            <body>
                                <div class="mainDivStyle">
                                    <h1 >Fading image</h1>
                                    <img id="picture" src="Central 3 Framed.png" class="imageStyle"/>
                                    <div class="otherDivStyle">
                                        <img src="Decrease.png" class="buttonSytle" onclick='changeOpacity(-0.1)'/>
                                        <img src="Increase.png" class="buttonSytle" onclick='changeOpacity(0.1)'/>
                                    </div>
                                </div>
                                <script type="text/javascript">
                                    sngCurrentOpacity=0.5;
                                    document.getElementById("picture").style.opacity=sngCurrentOpacity;
                                </script>
                            </body>
                        </html>
                    

Listing 2 above should be explained alongside Fig 1 since since the latter is a wireframe design for the HTML code.

Wireframe%20for%20fading%20image page
Fig 1

The <body> block spans lines 8 to 21 of Listing 2 and is represented in Fig 1 as the white perimeter. Within the <body> are two <div> elements.

The first <div> spans lines 9 to 16. It contains the main heading at line 10, an image at line 11 and the second <div> spanning lines 12 to 15.

Inside the second <div>, at lines 13 and 14 are two buttons Both buttons have an onclick property. Both buttons call the same function, changeOpacity() but one calls it with a negative parameter and the other with a positive parameter.

We shall talk more about those buttons when we examine the JavaScript code below.

Listing 3
                        let sngCurrentOpacity = 1;
                        const changeOpacity = (par) => {
                            sngCurrentOpacity += par;
                            if (sngCurrentOpacity > 1) {
                                sngCurrentOpacity = 1;
                            } else if (sngCurrentOpacity < 0) {
                                sngCurrentOpacity = 0;
                            }
                            const pictureElement = document.getElementById("picture");
                            if (pictureElement) {
                                pictureElement.style.opacity = sngCurrentOpacity;
                            } else {
                                console.error("Element with ID 'picture' not found.");
                            }
                        };
                    

In JavaScript the property opacity varies between zero and 1. If an image has an opacity of zero then it is not visible, while an image with an opacity of 1 is totally visible

In lines 18 and 19 of Listing 2 the opacity of the image is set to 0.5, which means that the image is visible but the background can be see through it.

Now let us look at changeOpacity() in some detail. Its entire use is ensuring that the variable sngCurrentOpacity stays within the values 0 and 1 and can move freely between those two limits.

The function has a parameter par which is passed to it from either line 13 or line 14 of Listing 2. If it is passed from Line 13 then the parameter is negative and thus it will reduce the value of sngCurrentOpacity when added to it at line 3. If it is passed from line 14 then it will be positive and therefore will increase the value of sngCurrentOpacity when added to it at line 3.

Once sngCurrentOpacity has been updated at line 3, lines 4 to 8 are devoted to ensuring that it does not go above 1 or below zero. At lines 4 and 5 it is tested for being above 1. If this is the case then it is reset back to 1. Similarly at lines 6 and 7, if it is below zero then at line 7 it is reset back to zero.

At lines 9 - 14 the opacity of the image is set to the current value of sngCurrentOpacity provided that the picture has been found.

You can test the application below.

Go to top

Summary

This document is a webpage titled "JavaScript | Fading Images," designed to teach the concept of image opacity manipulation using JavaScript. The content is organized into sections, with a header introducing the topic, a navigation menu, and an interactive main section. The learning outcomes are clearly stated: by the end of the lesson, users will understand how to increase or decrease the opacity of an image interactively.

The introduction explains the lesson's purpose, which is to explore JavaScript functionality through a simple application involving opacity changes in images. It emphasizes the separation of HTML, CSS, and JavaScript into different files for modularity, despite the simplicity of the example.

A detailed explanation of the concept of opacity is provided, describing how an image with full opacity (1) is fully visible, whereas an image with zero opacity is completely transparent. This section includes an example with images demonstrating varying opacity values and a wireframe diagram illustrating the layout of the HTML elements.

The CSS code snippet styles the page with a centered layout, specific dimensions, and a dark grey background for the main container. Additional styles are applied to align the images and buttons within the design framework, ensuring a visually appealing presentation.

The HTML structure contains two nested

elements. The outer container includes a heading, an image, and an inner container holding two buttons. The buttons are linked to JavaScript functions, allowing users to interactively adjust the opacity of the image using "+" and "−" controls.

The JavaScript code implements a function, changeOpacity(), to modify the image's opacity dynamically. The function ensures that opacity values stay within the range of 0 to 1. Users can increase or decrease the opacity incrementally by interacting with the buttons. The current opacity value is updated and applied to the image element in real time.

In conclusion, the page provides a complete and interactive example of how JavaScript, HTML, and CSS work together to create dynamic web functionalities. A live iframe demonstration is embedded to allow users to test the opacity manipulation feature in action.

Go to top

Revision

Multi choice

Fill in the blanks

Go to top

Assignment

For this assignment, you will create a simple interactive webpage to demonstrate your understanding of opacity manipulation using JavaScript. The task is based on the concepts outlined in the "Fading Images" lesson. You are required to use HTML, CSS, and JavaScript to create a functional and aesthetically pleasing webpage. The focus will be on implementing a feature to dynamically adjust the opacity of an image using buttons.

Begin by designing a basic HTML structure for your webpage. Include a main container that holds a heading, an image, and a set of buttons. The buttons should allow users to increase or decrease the opacity of the image. Ensure your HTML is well-structured and follows best practices.

Next, create a CSS file to style your webpage. Use the provided example as inspiration, but feel free to modify colors, dimensions, and other styling properties to make the page unique. Your CSS should include styles for the main container, buttons, and image. Pay special attention to layout and alignment to ensure the page is visually appealing.

Finally, write a JavaScript function to handle the opacity adjustments. Your function should dynamically update the image's opacity based on user interactions with the buttons. Ensure the opacity value remains within the valid range of 0 to 1, and use appropriate error handling to account for edge cases.

Submit your assignment as a zipped folder containing all necessary files (HTML, CSS, and JavaScript). Include comments in your code to explain your logic and design choices. Additionally, provide a brief description of how your webpage works and how the concepts of opacity and interactivity are implemented.

This assignment will assess your ability to integrate HTML, CSS, and JavaScript into a cohesive project. It will also evaluate your understanding of opacity manipulation and your ability to create an interactive user experience. Good luck, and enjoy experimenting with these exciting web development concepts!

Go to top