DevDiary



Get and Set, Text and Image

Event Listener and Promise Example

This page changes the text in a textbox and the displayed image when the user clicks on one of the buttons.

The example involves using an event listener and an asynchronous function to get data from a JSON file.

jQuery is used as well for the fade out and fade in animations.

This page can be viewed here.



HTML

JSON



Set Default Values

Set Image and Button Colour

At the start of the code a few variables are set up. The dataURL shows the URL where the JSON file exists.

This files contains all the data needed for this page.

The initial image is set.

Also the first button is set to red.



Async Function

Get Data from JSON File

When the page loads this function runs.

The data from the JSON file is loaded to an empty array.



Event Listener

Button Clicked

This for-loop contains a function which adds an event listener to all of the input elements (11 buttons).

If one of the buttons is clicked the function executes.



For Loop

Set All Buttons to Black

The loop sets the colour of all of the buttons to black.

After this loop the button that triggered the function, is set to red.



Event.Target.Style

Set Colour of Clicked Button

This changes the clicked button to the colour red.



jQuery: Fade Out, Callback and Fade In

Change Text and Image

The current image is faded out and then this function executes.

The image and text are changed using the "i" variable and the dataArray to determine the required data.

Then the image is faded back in.



Chrome Console