1

I`m working on an interactive story using Jquery. My question is; I want to change the text everytime I click in a button to the next dialogue function, so I created an object with some functions that contains the dialogues. Since it's an object, not an array, how can I access it's elements by click count?

story ={ 
    dialogue: function(){
     $("p").text("My name is Richard");  
    },
     dialogue: function(){
     $('p').text("Nice to meet you!").hide().fadeIn(1000); 
    },
     dialogue: function(){
     $('p').text("what is your name").hide().fadeIn(1000); 
    }
};


var clickCount = 0;

var nextStatment = function() {
  $('p').text(story[clickCount]).hide().fadeIn(1000);
  clickCount++;

};

$('.slideBt1').on('click', nextStatment);

3 Answers 3

4

You can use an array to store the text and use that with indexes to set the next content

story = ["My name is Richard", "Nice to meet you!", "what is your name"];

var clickCount = 0;
var nextStatment = function() {
  $('p').hide().text(story[clickCount] || '').fadeIn(1000);
  clickCount++;

};

$('.slideBt1').on('click', nextStatment);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Click to start</p>
<button class="slideBt1">Next</button>

Sign up to request clarification or add additional context in comments.

Comments

2

Following the next specification (https://www.rfc-editor.org/rfc/rfc7159#section-4) you can find that

The names within an object SHOULD be unique. ... An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.

You should re-write your object, using unique keys or array.

Comments

1

Maybe try making story an Array of functions?

story = [ 
    function(){
     $("p").text("My name is Richard");  
    },
     function(){
     $('p').text("Nice to meet you!").hide().fadeIn(1000); 
    },
     function(){
     $('p').text("what is your name").hide().fadeIn(1000); 
    }
];


var clickCount = 0;

var nextStatment = function() {
  $('p').text(story[clickCount]).hide().fadeIn(1000);
  clickCount++;

};

$('.slideBt1').on('click', nextStatment);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.