Home > other >  Jquery: Get the texts from a txt file
Jquery: Get the texts from a txt file

Time:10-01

I'm new to Jquery. I made a simple text/quote slider that calls the texts from the same html file, but I need it to get the texts from an external ".txt" file instead. I'm intended to use this slider in many other pages, and I don't want to edit each page when I want to edit/remove these texts.

I've read that $('#div-name').load("../textfile.txt") method would do the the trick, but I can't make it work with my slider although I tested it in a server. Do you maybe know how to do it? Here's my code:

HTML:

<div id="updates">
    <a href="redirect-link1.html">Text 1</a>
    <a href="redirect-link2.html">Text 2</a>
    <a href="redirect-link3.html">Text 3</a>
</div>

CSS:

#updates {
    width: 100%;
    height: 100px;
    float: left;
    text-align: center;
    background: rgb(255,255,255);
}
#updates a {
    width: 100%;
    color: rgb(0,0,0);
    font-size: 25px;
    line-height: 100px;
    text-decoration: none;
    display: inline-block;
}

JS:

$(function () {
var slider = $("#updates"),
    items = slider.children('a'),
    length = items.length,
    i = 0,

    change = function () {
        items.eq(i).fadeOut(300, function () {
            i  = 1;
            if (i === length) {
                i = 0;
            }
            items.eq(i).fadeIn(300);
        });
    };
    items.not(':first').hide();
    setInterval(change, 5000);
});

CodePudding user response:

$.get method is what you looking for.

EDIT 1: change method edit removed .txt empty lines

EDIT 2: dump links testing

EDIT 3: using links from an external file

jQuery(function () {
  const
    // Items container
    slider = jQuery("#updates"),
    // Text file containing links
    url = "https://raw.githubusercontent.com/decryptingfuture/placeholders/main/links.txt"

  // Initial iteration
  let i = 0

  // Get text contents
  jQuery.get(url, function (data) {
    // Split lines and iterate them
    data.split('\n').map((block) => {
      // Skip empty lines
      if (block !== '') {
        // Append each line to the container
        slider.append(block)
      }
    })

    // Children to be slided
    const items = slider.children()

    change = function () {
      items.eq(i).fadeOut(100, function () {
          i;

        if (i >= items.length) i = 0

        items.eq(i).fadeIn(100)
      })
    }

    items.not(':first').hide()

    setInterval(change, 500)
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="updates"></div>

  • Related