How to Display Random Javascript Snippets

How to Display Random Javascript Snippets thumbnail
JavaScript allows you to display randomized text snippets.

JavaScript represents a way for programmers to build interactive Web pages that can react to users, or display dynamically changing data. Because of this, JavaScript is a prominent scripting languages used in Web development. One of JavaScript's strengths is its ability to use many concepts and syntactical expressions from other, more "advanced" languages. Using the concept of arrays and importing external source code, you can create display snippets of text on your Web page that changes each time a user visits.

Things You'll Need

  • Text Editor
  • Web Browser
Show More

Instructions

    • 1

      Create an external file for snippets. This file will contain the JavaScript code that contains and displays the snippets. Save the file as "snippets.js."

      var snippets = new Array();

      snippets[0] = /*snippet string*/;
      snippets[1] = /*snippet*/;
      snippets[2] = /*snippet*/;

      function displaySnippet(index){

      document.write(snippets[index]);
      }

    • 2

      Import the snippets file into an HTML document. The HTML document is where the snippets will display:

      <html>
      <head>
      <script src = "snippets.js"></script>
      </head>
      </html>

    • 3

      Call the displaySnippet() function in the HTML document with a random number. This will call the function from the "snippets.js" file with a random index and display it to the page:

      <html>
      <head>
      <script src = "snippets.js"></script>
      </head>
      </html>

      <body onLoad="displaySnippet(Math.floor(Math.random()*4)">

Related Searches:

References

  • Photo Credit PhotoObjects.net/PhotoObjects.net/Getty Images

Comments

Related Ads

Featured