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

Converting a 'div' element into a dropdown menu with CSS and Jquery

I am facing a challenge where I have a collection of buttons enclosed in a div that I want to resemble a dropdown: <div id = "group"> <label> Group: </ label> <div value =" 1hour "> 1h < / div> <div value =" 2hou ...

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

Tips for incorporating an additional dataset bar using chart.js

I'm having a bit of trouble trying to modify the following script. Currently, it only displays one bar per label, but I need it to show 2 bars per label. Despite my numerous attempts using different variations with and without commas and "{}", I can&a ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Express template failing to connect with scripts, css, and images

When using Express, I encounter difficulty in getting the css, js, and images to link up correctly when running the index.html file. The images are not showing up and the css and js files are not linking properly. <link rel="stylesheet" type="text/css" ...

Grayscale effect not displaying on hover in Internet Explorer 9

Seeking assistance with a mouseover state issue in IE9 that I am experiencing. Since this element will vary in size, I am unsure about using a background image sprite. The problem arises when hovering over the item, as the image turns grey. However, when ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

What is the best way to ensure that my website's elements adjust automatically to different screen sizes?

Recently, I encountered a small snippet of HTML code with the main focus being an h2 element. #top-warning{ justify-content: center !important; display: flex; width: 100%; margin-top: 5vw; letter-spacing: 3px; font-family: "Penguin Regular ...

Video margins within a webview

After numerous attempts to embed a YouTube video in a WebView, I'm still struggling with a persistent small margin on the right side of the video. I've researched similar issues and attempted to address it through JavaScript adjustments without ...

How to send an email with an attachment using Codeigniter while utilizing PHP's mail function

I`m currently using the simple php mail() function to send emails in Codeigniter 2.1.2 with Bootstrap 2.3.2 and jQuery validation. It has been working well for me, but now I need to add an "attachment" field. I know that Codeigniter has its own email class ...

I'm new to Angular and I'm wondering how to close the panel by clicking on the 'x' button and also by clicking on the screen. Can anyone help me with this

Below is the HTML code I use for my button: <button class="btn btn-outlined " ng-click="vm.showCommentBox1()">Notify All</button> <div class="comment-box custom saveAll" ng-if=""><div class="panel panel-default"> ...

What is the best way to combine key-value pairs objects into a single object using JavaScript?

I am faced with the challenge of creating a new object that combines keys from a specific array (const props = []) and values from existing objects. If a key does not exist in an object, I aim to populate it with null or placeholder values. Here is my cur ...

The transitioning period caused the gooey effect to become distorted

I'm currently working on creating a radio button with a gooey effect. The transition looks great, but once it's complete, the colors don't blend well and the edges glow in an odd way. I've been searching for the root of the issue, but ...

I'm facing challenges with setting auto heights on CSS and aligning floating divs

I'm trying to create a simple tiled list with six smaller divs inside a main div, all set to float:left. However, this is causing issues with the auto height and it doesn't seem to work properly within the div. Can anyone help me fix my code or s ...

Adjusting Window Size Causes White Space to Appear Above Div

I currently have two inline-block div in my post page that showcase my latest book reviews. Typically, these sections align perfectly and occupy the same amount of space on the screen. However, for certain window sizes, one of the inline-block elements end ...

One way to add a JSON object to an empty JSON array using Javascript involves pushing

Currently, I am facing an issue with an empty JSON array. shoppingCart: [] In addition to the empty array, I also have a JSON object defined as follows: let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"}; M ...

What is the best way to upload a local image using JavaScript for TensorFlow?

I am having trouble loading a data.jpg file to be used by tensorflow mobilenet. When I try to require the file normally, I encounter an error message: So, my question is how can I load an image in my JavaScript code for use? I have tried various methods of ...

Image not yet clicked on the first try

I am encountering an issue with my image gallery. Currently, when I click on a thumbnail, the large image is displayed. However, I would like the first image to show up without requiring the user to click on its thumbnail. How can I address this problem? B ...

Reorganize Information in Table with the Help of jQuery's each Method

I have a collection of data retrieved from the database with varying prices and some redundant information. Here's a snapshot of the data: The desired format for the data is shown in this table: My attempt to organize the data using jQuery, specific ...

What is the best method for aggregating multiple JSON responses into a single array?

I am struggling to get my data in the desired format of [{..},{..},{..}]. I have created an empty array using const arr = [], but when I push all JSON data into this array, the output shows as separate arrays. How can I fix this issue? // const arr = [] co ...