Retrieving a completely random caption from a text file with JavaScript and showcasing it in HTML

I need help loading a random caption each time my page loads. I have a text file with a string on each line, but I'm new to HTML and JavaScript.

Here's my code:

<div class="centerpiece">
                <h1>DEL NORTE BANQUEST</h1>
                <p class="caption"><script src = "js/caption.js"></script><script>getCaption();</script></p>
                <a class="btn" id="browse-videos-button" href="#video-list">Browse Videos<br><img src="img/arrow-down.svg"style="width:15px;height:15px;"></a>
            </div>

This is my JavaScript function:

function getCaption()
{
  var txtFile = "text/captions.txt"
  var file = new File(txtFile);
  file.open("r");
  var str = "";
  var numLines = 0;
  while (!file.eof)
  {
      numLines += 1;
  }
  file.close();
  file.open("r");
  var selectLine = Math.getRandomInt(0,numLines);
  var currentLine = 0;
  while(selectLine != currentLine)
  {
    currentLine += 1;
  }
  if(selectLine = currentLine)
  {
    str = file.readln();
  }
  file.close();
  return str;
}

Text in Source File:

We talked yesterday
Freshman boys!
5/10
I'm having a heart attack *pounds chest super hard

The website is for my high school cross country team, just in case the text file confused you.

I'm still learning and not sure about all the syntax. I had some issues iterating through the file, so I opened and closed it twice. Here's a jsfiddle of what I'm trying to achieve:

https://jsfiddle.net/7cre9qqj/

If you need more code or have any critiques, please let me know. I appreciate any help and feedback as I continue to learn. Thank you!

Answer №1

Utilizing the File API grants access to the file system on the user's end, making it less suitable for your specific needs. Moreover, its usage is restricted to certain scenarios.

An alternative approach involves executing an AJAX request to populate your desired quote. By making a server-side call, you can read the file and easily split its contents by line to select a random one for display. Given that you are willing to explore jQuery, implementing the code is relatively straightforward:

$.get("text/captions.txt")).then(function(data) {
  var lines = data.split('\n');
  var index = Math.floor(Math.random() * lines.length);
  $("#quote").html(lines[index]);
});

For a visual demonstration, here's a fiddle showcasing the entire process; each execution will present a different random quote: https://jsfiddle.net/s1w8x4ff/

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

Modify the button's color when clicked and add it to an array with JavaScript

I am currently working on changing the color of buttons to indicate a selection. When a button is selected, its value is added to an array. If the same button is clicked again, it becomes unselected and its color reverts back to the original state, with it ...

Retrieving the value from an Object within a Mongoose query result

My query looks like this const result = await Form.findOne({ _id: req.params.id }); And here is the output of my query: { _id: 5a8ea110d7371b7e5040d5c9, _user: 5a5c277f8d82ba3644b971c2, formDate: 2018-02-22T10:53:04.579Z, formElement: { form ...

Provide a response containing JSON data extracted from an HTML file

I am looking for a way to create a simple REST API using a hosting site that only allows hosting of HTML files along with JavaScript files. I want to be able to send POST/GET requests and receive JSON data in response. For instance, when making a GET requ ...

Combining images with PHP

I have a collection of numerous images that are all the same size in terms of width and height. In total, there are over 50 unique images. My goal is to combine these images along both the horizontal (X) and vertical (Y) axes. Specifically, I would like ...

Change the selection so that only the initial one appears in gray

Is there a way to make the text inside a select field gray out when the first option is selected? Can this be accomplished with just CSS or does it require JS? I have attempted altering the style of the first option, but it only affects the text color in ...

JavaScriptCore now includes the loading of AMD modules

I am trying to incorporate a JavaScript module into JavascriptCore on iOS. To achieve this, I am fetching the file's text through a standard HTTP request on the iOS platform. Once I have obtained the entire string, I plan to parse it into the JSconte ...

Having issues with image hover and click functionality

My website has an image with the cursor set to pointer and a function that should show a hidden element when clicked. However, it's not working at all. When I hover over it or click on it, nothing happens. Here is a screenshot of the issue along with ...

"Challenges arise with content layout when the screen size shrinks in

Having trouble with the layout on smaller screens - I want the image above the button but below the text. I'm new to bootstrap and haven't been able to figure it out by reading the docs. Can someone please help me identify the issue and explain w ...

Naming variables in JavaScript with parentheses()

I'm currently facing some issues with my code, as it's not working properly. I have three variables that set the state of another set of three variables. Instead of writing out the code three times, I wanted to use another variable (like 'i& ...

Adjust the height of the second column in Bootstrap 4 textarea to fill the remaining space

I am facing an issue with my layout where I have 2 columns, one containing some inputs and the other only a textarea. The problem is that I want the textarea in the second column to extend and fill the remaining height of the first column, but so far I hav ...

What is the best way to add a refresh link to my CAPTCHA script?

I have a captcha script that is functioning well. However, I am struggling to figure out how to implement a refresh function for it. Below is the code from verificationimage.php: <?php header('Content-type: image/jpeg'); $width = 50; $heig ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

Using an array of objects with useState

I have a search box where I can paste a column from Excel. Upon input, I parse the data and create an array of entries. Next, I loop through each entry and utilize a custom hook to retrieve information from my graphql endpoint. For instance: If 3 entrie ...

Is there a way to condense my child table directly below its parent column?

When attempting to collapse the "child tr" within the "tr" in my code, the collapse is not positioning correctly underneath its parent tr. While it works fine in a JSFiddle, the issue arises when using my editor and live preview. In this scenario, both "ch ...

Utilize jQuery to manipulate a subset of an array, resulting in the creation of a new array through the use of

I have a string formatted like this: ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, up to item 25). My task is to take an index provided by the user (for example, 2), retrieve the item at that index when ...

Change the order of columns using CSS in a mobile-first approach

Is there a way to achieve the layout shown in the image using only HTML and CSS? I attempted rearranging the stacked elements for larger screens by: #2: float: left #1: display: inline-block #3: float: right However, this approach did not yield the desi ...

Bootstrap grid for thumbnails

I am attempting to create a responsive grid with thumbnails using Bootstrap and Knockout. Here is the current HTML code: <div class="row"> <!-- ko if: toys().length == 0 --> <div>No toys in category</div> <!-- /ko -- ...

Is it necessary to utilize multiple v-models in Vue.js 2 in order to bind values to a form component?

Currently, I am developing a basic form component that includes input fields for first name, last name, email, and phone number. I want to pass the user object to prefill the form and make changes using just one v-model. This is my initial code. <div& ...

How to Set a Button as Inline Text in a React Native Component

Below is the code snippet I am working with utilizing the Text and Button components provided by react-native-paper: <Text>See also </Text> <Button mode="text" compact onPress={this.nav( name )}>Compass</Button> <Text&g ...

How can I apply various textures in three.js?

Hello there! I'm diving into the world of threejs and currently working on a block game similar to Minecraft. Instead of relying solely on objects, I've decided to build my program using planes (specifically the PlaneGeometry class). As I wrap ...