Hey, everyone! In this Tutorial, we’ll explore HTML with Javascript, demonstrating an alphabet spin from A to Z Similar to Instagram’s video effect/filter where an alphabet spins from A to Z on top of the head, we’ll also pick a random letter from A to Z and display it.
In the World of Web Development JavaScript plays an top important role in giving or adding interactive dynamic features like animation to web apps. On fascinating Example is here to Spin the Alphabets from A-Z and generate a random alphabet from it and display it.
Video Tutorial
Source Code
html
<!DOCTYPE html> <html> <head> <title>Hello World!</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <h1 class="title">Hello World! </h1> <div id="alpha">A</div> <script src="script.js"></script> </body> </html>
Here In HTML Code I have added a div container with id as “alpha” so that i can control div tag from javascript code.
Javascript
var alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var i = 0; var loopNo = 0; function update() { document.getElementById('alpha').innerHTML = alphabets[i]; i++; if(i == alphabets.length){ i = 0; loopNo++; } if(loopNo == 1){ var randomIndex = Math.floor(Math.random() * alphabets.length); var randomAlphabets = alphabets[randomIndex]; console.log(randomIndex); clearInterval(intervalId); document.getElementById('alpha').innerHTML = randomAlphabets; } } var intervalId = setInterval(update, 100);
Now, let’s check out the javascript code to interact with HTML. The <div> tag/element by using its id ‘alpha’ where the alphabets will be dynamically displayed rapidly A-Z in a loop wise.
Code Walkthrough:
- Alphabets Array: The script initializes a string
alphabets
containing all uppercase English letters. - Variables Initialization: Two variables,
i
andloopNo
, are initialized to keep track of the current alphabet index and the number of loops. - Update Function: The
update()
function is responsible for updating the content of an HTML element with the id ‘alpha’ with the current alphabet. - Loop Control: The function increments the index
i
and resets it to 0 when it reaches the length of the alphabet string, simulating a continuous loop. - Random Alphabet Generation: After the first loop (
loopNo == 1
), the code selects a random index from the alphabet string and displays the corresponding letter. ThesetInterval
is then cleared, stopping the continuous update.
Conclusion:
In conclusion, This JavaScript code help you in understanding basic of JS like how to make use of setInterval() to call a function repeatedly and perform an event like dynamically changing HTML div tag TextContent and also how to stop the setInterval() using clearInterval(). Such scripts can be used for educational purposes, creating interactive quizzes, or simply for adding a playful touch to a website.