Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate:

  1. The new text is added above the old text instead of below it, pushing the older text down the page as the game progresses.
  2. As the text moves down the page, it gradually fades out of view.

I'm currently stuck on accomplishing #1. I believe using something like insertAfter instead of

InsertBefore</code might be helpful, but I'm not sure.</p>

<p>My current code looks like this:</p>

<p><code>$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);

However, this inserts the new text below any existing text.

Regarding #2, I think placing the text inside a div and setting overflow: hidden could work. I suspect there might be some JavaScript or CSS that can make it gradually fade out as it moves lower on the page. This is where I feel stuck.

I thought the following might hold the answer:

$(window).scroll(function () {
    var scrollTop = $(window).scrollTop();
    var height = $(window).height();
    $('.logo_container, .slogan').css({
        'opacity': ((height - scrollTop) / height)
    });
});

I came across a fiddle here http://jsfiddle.net/0ma4na3t/1/ that somewhat achieves this effect with a div. However, I'm confused about where .slogan comes from in that fiddle. It doesn't seem to appear in the code provided. Is it a jQuery or JS command?

Answer №1

If you prefer using pure Javascript, executing the task is relatively straightforward. In this context, I am limiting the display to a maximum of 10 sentences, ensuring that any surplus sentences are omitted. This functionality could be easily customized based on your window size preferences.

function prependAndFade(item, text){
    // Locate the designated item for pre-pending
    var p = document.getElementById(item);
    // Generate a new paragraph and insert the content
    var e = document.createElement('p');
        e.textContent = text;

    // Add the paragraph (at the beginning or as the sole child)
    if(p.childNodes.length) p.insertBefore(e, p.childNodes[0])
    else p.appendChild(e);
  
    // Implement a timeout to enable CSS fading effect on the text
    setTimeout(function(){
        // Iterate through each element, decreasing opacity until reaching 10
        for(var o = 1, i = 0; i < p.childNodes.length; i++){
            // Verify if the childNode is a P tag
            // As empty spaces etc. are also children but not elements
            if(p.childNodes[i].tagName === 'P'){
                o-=.1
                p.childNodes[i].style.opacity = o;
            }
            // If the opacity reaches 0, remove the remaining elements (conserve resources)
            if(o === 0) p.removeChild(p.childNodes[i]);
        }
    }, 100);
}
p {
  opacity: 0;
  -webkit-transition: opacity 500ms;
  transition: opacity 500ms;
}
<input type="text" onchange="prependAndFade('fader', this.value); this.value = '';" />

<dfiv id="fader"></div>

Answer №2

If you have a set height for your container div with a specified maximum number of lines, you can achieve an effect by adjusting the opacity of each line and using jQuery's prepend() function to add them dynamically:

EXAMPLE:

HTML

<input type="text" id="text"></input>
<button id="submit">submit</button>
<div id="container"></div>

CSS

#container {
    width: 500px;
    height: 100px;
    overflow: hidden;
}
.line {
    display: block;
}
.line:nth-of-type(3) {
    opacity: 0.7;
}
.line:nth-of-type(4) {
    opacity: 0.3;
}
.line:nth-of-type(5) {
    opacity: 0.1;
}

Javascript

$("#submit").on("click", function () {
    $("#container").prepend($("<span class='line'>" + $("#text").val() + "</span>"));
});

FIDDLE

Enter some text in the textbox and click submit to see the effect on the lines.

Answer №3

To achieve the desired effect, you can utilize CSS styling by targeting specific list items in this way:

li:nth-child(1) {
    opacity:1;
}

li:nth-child(2) {
    opacity:0.8;
}

li:nth-child(3) {
    opacity:0.6;
}

etc...

Subsequently, dynamically adding elements to the unordered list can be done as follows:

var i = 0;

$('#add').click(function () {
    $('#container').prepend('<li>line ' + i + '</li>');
    $('#container li:gt(4)').remove();
    i += 1;
});

A demonstration of this technique using jQuery is available on JSFiddle: https://jsfiddle.net/51uh50my/

Answer №4

To create a visually appealing effect as items are added to the list, consider using a gradient overlay with varying opacities to gradually 'fade out' the text. This approach will address point #2

If you need help in generating the right gradient combination, you can utilize this editor:

For addressing point #1, you can simply employ jQuery's prepend function to add a new div element to a specific container, thus creating a new line for each entry

$(document).on('click', '.addResponse', function(){
  $('.response_container').prepend('<div>' + $('.myInput').val() + '</div>');
});
.gradient_overlay {
  background: -moz-linear-gradient(top, rgba(255,137,137,0) 0%, rgba(255,48,48,0.5) 50%, rgba(255,50,50,1) 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,137,137,0)), color-stop(50%,rgba(255,48,48,0.5)), color-stop(100%,rgba(255,50,50,1)));
  background: -webkit-linear-gradient(top, rgba(255,137,137,0) 0%,rgba(255,48,48,0.5) 50%,rgba(255,50,50,1) 100%);
  background: -o-linear-gradient(top, rgba(255,137,137,0) 0%,rgba(255,48,48,0.5) 50%,rgba(255,50,50,1) 100%);
  background: -ms-linear-gradient(top, rgba(255,137,137,0) 0%,rgba(255,48,48,0.5) 50%,rgba(255,50,50,1) 100%);
  background: linear-gradient(to bottom, rgba(255,137,137,0) 0%,rgba(255,48,48,0.5) 50%,rgba(255,50,50,1) 100%);
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00ff8989', endColorstr='#ff3232',GradientType=0);
  
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}

.response_container {
  height: 1000px;
}

.input_container {
  z-index: 10;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_container">
  <input class="myInput" type="text"/><button class="addResponse">Add Item</button>
</div>
<div class="response_container">
  <div class="gradient_overlay"></div>
</div>

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

The $watchCollection function will consistently have the identical object assigned to both the new and old values

When using $watchCollection to monitor an object, how can I determine which property of the object has been changed? The problem I am facing is that in the callback function, the new and old values are both the same objects. Is there a way to watch an obje ...

The submit button fails to produce any result

I have a submit button in a contact form that triggers PHP code to send an email. However, when I press the button nothing happens - not even the PHP code is displayed as it should be if PHP were not installed. Interestingly, I have tested other simple mai ...

Is it possible to save round items within a session?

While utilizing Blocktrail's API for bitcoin wallet management, I encountered an issue with circular references within the returned wallet object. The goal is to store the decrypted wallet in the user's session to avoid password re-entry. Howeve ...

The number range filter in ng-table is malfunctioning

what I am trying to accomplish My goal is to create a column that can accommodate two numbers in order to filter numeric data within a specific range for that column. While sorting, pagination, and filtering by 'contain text' are working correct ...

Uncover comprehensive error analysis via AJAX communication

I am seeking a more comprehensive response regarding a domain through the use of ajax. Currently, I possess the following code: $.ajax({ url: domain, type: "POST", data: { //To identify any errors, an empty response is set xml ...

The font from the server is not displaying correctly in the local HTML file

After uploading the ttf font file to the server, I utilized the following CSS code: @font-face { font-family: "fontname"; src: url("http://www.mywebsite.com/Fonts/fontname.ttf"); } body { font-family: "fontname", sans-serif; } Within the loc ...

Optimizing CSS usage within Django: top recommendations

Throughout a 6-month-long project, I have continuously added new URLs. However, I am now encountering an issue when using the extend 'base.html' function on other pages where the CSS overlaps and creates confusion. My question is: What are the b ...

Attempting to send an email through a contact form using jquery-validation, successfully passing all validation checks yet not receiving the email

My goal is to master the process of creating a form, validating the input, sanitizing the data, and sending it to myself via email. To kick things off, I crafted an HTML form and incorporated the fantastic jquery-validation plugin found here. The frontend ...

Controlling the file selection window of a browser with protractor/jasmine

The tools I am currently using are Protractor 3.3.0, Jasmine 2.4.1, and Selenium Standalone Server. My main objective is to create a test scenario where the test navigates to a specific page and then clicks on an 'upload file' button. This actio ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Intrigued by the prospect of making HTML elements vanish or smoothly glide along with the content without obstructing it

I'm a beginner in coding and I want to make my website impressive. Right now, I have an HTML embedded element called "On this Page" that I would like to disappear when the user scrolls down the page. I've managed to position the element on the ...

Tips for moving an element to the end of an array

Patients' data is stored in the MongoDB database, and all patients are mapped through on the frontend to display a list. An additional boolean value indicates whether a patient is archived or not. If a patient is archived, it should be displayed at th ...

Why am I encountering a type error in NodeJS when utilizing the ping module?

I'm currently working on creating a simple app for pinging an IP address. The HTML form I've created has one input field for the IP address, which is then sent to NodeJS for processing. I am utilizing the ping module to retrieve the results. Ever ...

New patch request received in Google Sheets, replacing the existing post request

I am transferring 12 cell values from a Google Sheet to a MongoDB database. The purpose behind this action is to merge the 12 cells, perform certain data transformations, and display the output on a frontend interface later on. Moreover, I'm faced wit ...

Use ng-class in a P tag to assess a variety of expressions

Is there a way to apply ng-class to automatically evaluate negative values within a < p > tag? <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{d.l ...

Can an HTML DIV be resized along with its contents?

Is it possible to scale a container with animated elements inside to fit the browser window, or do you have to adjust each child element individually? ...

I made a request using the post type fetch to submit data to this form, but unfortunately, the server-side response returned

I encountered an issue where after sending the post type fetch to this form, I received 'undefined' on the server side. Here's the code snippet for my fetch request: const { text, id } = Data; fetch('http://localhost:3001/add' ...

"Entering a text message will prompt the appearance of the on-screen keyboard in capital

Our website is optimized for use on Android tablets. I have added the following CSS to the input's class: text-transform: uppercase; While this successfully displays typed letters in uppercase, it does not change the appearance of the on-screen keyb ...

Displaying JavaScript Array Elements in an Aligned Table Format

Unfortunately, I accidentally deleted my previous post and now need to repost it. I have a code that is functioning well, thanks to the great help I received here. However, the output of the array players is not neatly aligned with each other in a table f ...

What is the process for deleting an event in Vue?

My Vue instance currently includes the following code: async mounted () { document.addEventListener('paste', this.onPasteEvent) }, beforeDestroy () { document.removeEventListener('paste', this.onPasteEvent) }, methods: { onPasteEv ...