user3657515
user3657515

Reputation: 3

How do I display a single new word of a paragraph at a time, moving by keypress or mouseclick?

Say I have something like this:

<p>Here are several words in a sentence.</p>

I'm trying to figure out how to display each word, one by one, via keypress or mouseclick, till it reaches the end.

So for example:

Here (click)
Here are (click)
Here are several , etc.

This may be basic, but I'm not very good and I'd love some help!

Thanks!

Upvotes: 0

Views: 925

Answers (3)

Matthew Johnson
Matthew Johnson

Reputation: 5155

This has been turned into a jQuery Plugin: word-reveal.

While the other two answers will work (sort of), they aren't very reusable. What happens when you have more than one container you'd like to reveal with more than one sentence? I created a jQuery plugin that can easily be reused throughout the page.

The Setup

  • Include jQuery on the page
  • Download the plugin from GitHub, and include it on the page
  • You're set and ready to go!

The HTML

Set an id for each div or p tag. An example of multiple uses:

<p id="firstRevealer"></p>
<p id="secondRevealer"></p>
<p id="thirdRevealer"></p> 

The jQuery

$(document).ready(function() {
    $("#firstRevealer").wordReveal({text:"This reveals one word at a time."});
    $("#secondRevealer").wordReveal({text:"Adding more text is easy!"});
    $("#thirdRevealer").wordReveal({text:"It <b>also</b> works on <em>some</em> tags, since it splits on <b>spaces</b>!"});
});

The CSS

I added CSS on the example, to make clear where you're clicking to reveal the next word. A different answer registered clicks on the document, but any clicks (for a expandable menu, for example) would add a word.

p { 
    padding: 10px; 
    margin:10px; 
    min-height:25px; 
    background-color:#BADA55 
}

The fiddle.

Note

This can easily be extended to act on other events (keypress).

Upvotes: 0

FabKremer
FabKremer

Reputation: 2179

I just want to make some interventions on @Dean.DePue answer and make the code so you paste it in your project and does the trick:

Your html should look like this:

<div id="adiv"></div>

And you should add this javascript code too:

var index, newsentence, sentence, words;
sentence = "Here are several words in a sentence";
words = sentence.split(" ");
index = 0;
newsentence = "";

$(document).click(function(e) {
  if (e.button === 0 && index < words.length) {
    newsentence += words[index];
    newsentence += " ";
    $("#adiv").html(newsentence);
    index = index + 1;
  }
});

If you've got any doubt of the code just ask!

Upvotes: 1

Dean.DePue
Dean.DePue

Reputation: 1013

<script type="text/javascript">
var sentence = "Here are several words in a sentence";
var words = sentence.split(" ");
var index = 0;
var newsentence = "";
function clickit() {
  newsentence += sentence[index];
  index = index + 1;
}

Upvotes: 0

Related Questions