Create a smooth transition: How to make a hidden button appear after a function finishes in JavaScript

I am completely new to the world of JavaScript, HTML, and CSS, so I'm feeling a bit lost on how to proceed with this task.

My goal is to create a script that will initially display some text through a specific function. Once that text has been displayed, I want an HTML button (or something similar) to automatically fade in without requiring any user interaction. My assumption is that the button would need to be inserted beforehand and hidden somehow, and then its visibility would be adjusted to achieve the desired fade-in effect. Is this achievable with JavaScript, or are there potentially simpler methods that I should consider? Any guidance you can provide would be greatly appreciated.

Here is the code I have developed thus far:

<!DOCTYPE=HTML>
<html>
<head>
    <title>Sandbox</title>
    <link rel="stylesheet" href="mainstyle.css">
    <script src="main.js"></script>
</head>
<body>   
    <p id="pid"></p>
    <script>
    
        var a = 1;
        function dialogue(){
            var message = "This message is (hopefully) a successful implementation of JS video game scrolling! <br> <br> Pretty cool, huh? Well, believe it or not, this whole page is a test for a very basic interactive story using HTML/JavaScript! <br> <br> Let's see if we can add some fade-in buttons, shall we? <br> <br> (By the way--you can click anywhere in this window to instantly clear through subsequent text scrolls.)";
            if(a <= message.length) {
                var txt = message.substring(0,a);
                document.getElementById ("pid").innerHTML = txt;
                setTimeout("dialogue()",20);
                a++;
                document.onclick = function(){
                a = message.length;
                };
            }
        };

        dialogue();


    </script>
    <button id="button1">Ooh, here's one! Click to see what it does!</button>
</body>
</html>

Answer №1

If you want to display the button after reaching a certain length, tweak your code's condition accordingly.

Consider these enhancements:

  • Instead of passing a string as the first argument to setTimeout, opt for passing a function for better practice.

  • Avoid attaching a click handler every time dialogue is called; define it only once.

  • Try not to alter global variables within functions unless absolutely necessary.

  • When trimming a string with HTML tags, be cautious as it could lead to invalid HTML structure, especially if halfway through a tag like <br>; consider using plain text and setting the content via textContent property (or jQuery's text function), while utilizing CSS's white-space property for line breaks. You can define the string using backticks (ES6) for effortless line breaks with the enter key.

Personally, I prefer using setInterval over setTimeout:

var message = `This message is (hopefully) a successful implementation of JS video game scrolling!

Pretty cool, huh? Well, believe it or not, this whole page is a test for a very basic interactive story using HTML/JavaScript!

Let's see if we can add some fade-in buttons, shall we?

(By the way--you can click anywhere in this window to instantly clear through subsequent text scrolls.)`;

var timer = setInterval(dialogue, 20);

function dialogue(add = 1){ // By default 1 character is made visible
    var len = $("#pid").text().length + add; // Get desired length
    $("#pid").text(message.substr(0, len)); // Make the change
    if (len < message.length) return; // Nothing more to do
    clearInterval(timer); // All is shown, so stop the animation
    $("#button1").fadeIn(); // and fade in the button
};

// On click, pass the length of the message to the function
$(document).click(dialogue.bind(null, message.length));

// Hide the button on page load
$("#button1").hide();
#pid { white-space: pre-wrap }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="pid"></p>
<button id="button1">Ooh, here's one! Click to see what it does!</button>

Answer №2

To display the button after finishing writing the text, you can include this code within your if statement:

else{
    document.getElementById("button1").style.display = "block";
}

This code will make the button visible once you are done with writing, as the condition a <= message.length is false.

Example:

#button1{
display:none;}
<!DOCTYPE=HTML>
<html>
<head>
    <title>Sandbox</title>
    <link rel="stylesheet" href="mainstyle.css">
    <script src="main.js"></script>
</head>
<body>   
    <p id="pid"></p>
    <script>
    
        var a = 1;
        function dialogue(){
            var message = "This message is (hopefully) a successful implementation of JS video game scrolling! <br> <br> Pretty cool, huh? Well, believe it or not, this whole page is a test for a very basic interactive story using HTML/JavaScript! <br> <br> Let's see if we can add some fade-in buttons, shall we? <br> <br> (By the way--you can click anywhere in this window to instantly clear through subsequent text scrolls.)";
            if(a <= message.length) {
                var txt = message.substring(0,a);
                document.getElementById ("pid").innerHTML = txt;
                setTimeout("dialogue()",20);
                a++;
                document.onclick = function(){
                a = message.length;
                };
            }else{
              document.getElementById("button1").style.display = "block";
            }
        };

        dialogue();


    </script>
    <button id="button1">Ooh, here's one! Click to see what it does!</button>
</body>
</html>

Answer №3

Absolutely, it is definitely possible. If I understand correctly, all you need to do is add an else statement to the function and make sure the button becomes visible. Working with classes makes it easier to define a CSS fade-in effect for added visual appeal.

<!DOCTYPE=HTML>
<html>
<head>
    <title>Sandbox</title>
    <link rel="stylesheet" href="mainstyle.css">
    <script src="main.js"></script>
</head>
<body>   
    <p id="pid"></p>
    <script>
    
        var a = 1;
        function dialogue(){
            var message = "This message is (hopefully) a successful implementation of JS video game scrolling! <br> <br> Pretty cool, huh? Well, believe it or not, this whole page is a test for a very basic interactive story using HTML/JavaScript! <br> <br> Let's see if we can add some fade-in buttons, shall we? <br> <br> (By the way--you can click anywhere in this window to instantly clear through subsequent text scrolls.)";
            if(a <= message.length) {
                var txt = message.substring(0,a);
                document.getElementById("pid").innerHTML = txt;
                setTimeout("dialogue()",20);
                a++;
                document.onclick = function(){
                a = message.length;
                };
            }
            else {
                document.getElementById('button1').style = '';
            }
        };

        dialogue();


    </script>
    <button id="button1" style="display:none;">Ooh, here's one! Click to see what it does!</button>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we refresh the model in Angular.js from a section of the application that has not been 'angularized' yet?

UPDATE: Found a similar question at Call Angular JS from legacy code Working on adding a new feature to an existing application using Angular. Unable to do a complete rewrite, so the challenge is integrating Angular models with the rest of the app that di ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Connecting two tables in an express API

Currently, I am in the process of developing an API using Express.js. At this stage, my initial tests are functioning correctly. My goal now is to retrieve values from two separate tables. For example, consider the following 2 tables: Table_A Id: 1, Name: ...

Combining jqueryUI autocomplete and datalist for enhanced user input options

My search form in HTML has a single input field where users can enter three different things: area name, trek name, or other keywords. For areas not in a database, I have implemented a datalist field (HTML) connected to the input for autocompleting the a ...

Encountered a Webpack issue when trying to load the primeng.min

I recently initiated a fresh project using yo aspnetcore-spa. My goal is to integrate the PrimeNG component library. Upon installing font-awesome and primeng: npm install font-awesome primeng --save I included CSS in the webpack vendor list: vendor: [ ...

Convert your Node.js server URL hosted on AWS Elastic Beanstalk to HTTPS

Struggling to deploy my React JS app using AWS S3 bucket as I am new to the platform. The app communicates with a Node/Express server hosted on an Elastic Beanstalk environment. Encountered the error: Mixed Content: The page at 'https://myReactApp.s3. ...

Send the id of the chosen row to the Component tag within the blade file

I'm working on passing the id of the currently selected row within a for loop when it's clicked on. The goal is to then pass that id to a Vue component. In my index.blade file: @foreach($cats as $cat) <tr> <td class="catme" d ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Implementing a full-width search bar within the Bootstrap navbar

I'm trying to create a navbar using Bootstrap 3.7.7 with a logo on the left, links on the right in two rows, and a large search bar in the center. I've managed to align the logo and links correctly, but I'm struggling with sizing the search ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Incorporating JavaScript code within a partial response retrieved via AJAX

Is it frowned upon to include JavaScript within partials fetched via AJAX? Let's imagine a scenario where I have a button on that retrieves a form using AJAX. It is also desired to implement some jQuery event handlers for this form (such as validati ...

Sending handlebars variable to the client-side JavaScript file

I am currently working on an application using node.js along with express and handlebars, and I'm trying to find a way to transfer handlebars data from the server to client-side JavaScript files. Here is an example: //server.js var person = { na ...

"Learn how to securely redirect to a custom URI scheme with a fail-safe option to display alternative content if not supported

In short: Can a visitor be redirected to a custom URI scheme or shown alternate content if the scheme is not supported? My specific scenario involves developing a mobile app that utilizes a custom URI scheme for users to invite others to actions within th ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

React component is being rendered, but it is not mounting properly, so it is unable

In my FillForm functional component, I am calling a list of objects to be rendered sequentially within the FormFiller function. The components are rendering correctly, but I encounter an error when trying to change their internal state. Warning: Can&apos ...

Display information from a MySQL database in a tabular format using PHP

I am currently learning PHP and attempting to retrieve data from a database to display it in an HTML table. However, I am facing an issue where the total number of records returned is 13 but only 12 records are being displayed in the table (it seems to be ...

Table of Data: Enhancing row selection with icons

I have a dilemma regarding adding images to the left of text in specific columns within rows. A similar issue was faced by an individual (referenced here: jQuery DataTables add country icons to each column). The person wanted to include flag icons next to ...

Issue alert before running tests on component that includes a Material UI Tooltip

This is a follow-up regarding an issue on the Material-UI GitHub page. You can find more information here. Within my Registration component, there is a button that is initially disabled and should only be enabled after accepting terms and conditions by ch ...

ChartJS, introducing a new dataset

I'm looking for a way to showcase my 3 curves in a specific order: start with the first one, then after a 5000 interval, add the second curve, and finally, after another 5000 interval, include the third dataset. The code below currently updates a sin ...