Utilize the appendTo() function and make a switch to dynamically insert content stored in variables into a specified

I am working on developing a page with a central content div, where users have the ability to choose various options that will introduce different additional content. This added content will then present more opportunities for adding new elements, ultimately leading to the creation of an interactive short story.

After revising my approach slightly, I am still encountering issues trying to implement it.

The code I am currently using is as follows:

<div id="ongoingStory">
   <p>You find yourself in a certain place. There are items scattered around and multiple exits.</p>  
   <p>Would you like to take <span id="action1">action 1</span> or <span id="action2">action 2</span>?</p>
</div>

var oneResult = "<p>You decide on action 1, which triggers some events. You can then choose between <span id=\"action3\">action 3</span> or <span id=\"action4\">action 4</span>.</p>";
var anotherResult = "<p>Opting for action 2 leads to other outcomes. Afterward, you can select either <span id=\"action5\">action 5</span> or <span id=\"action6\">action 6</span>.</p>";

var root;
var branch;

function addToStory(root, branch) {
   $( "#" + root ).addClass( "disabled" );
   $(branch).appendTo("#ongoingStory").hide().fadeIn(1000);
}

document.getElementById("ongoingStory").addEventListener("click", moveAlong, false);

function moveAlong(e) {
   if (e.target !== e.currentTarget) {
      switch (e.target.id) {
         case action1:addToStory(action1, oneResult);break;
         case action2:addToStory(action2, anotherResult);break;
         case action3:addToStory(action3, otherResult);break;
         case action4:addToStory(action4, yetOtherResult);break;
      };
   };
   e.stopPropagation();
}

Upon loading the page, no errors occur, but clicking on an action within the initially displayed content inside the ongoingStory div does not trigger any changes. Subsequently, the console outputs a "ReferenceError: action3 is not defined." This error arises because the specified content containing that particular action/id tag is not being added. The challenge lies in understanding why this content is not appended in the first place. It is possible that there may be issues with how I am referencing the ID's of the spans, although if that were the case, I would anticipate the switch statement to encounter problems at action1 instead.

Answer №1

Your code has a few issues that need to be addressed. The best practices have been discussed in the chat room. One specific problem is missing quotes in this line:

case action1:addToStory( action1,oneResult );break;

To fix it, change it to:

        case 'action1':
            addToStory('action1', oneResult);
            break;

(make the same changes for all other actions)

You can also view a JSFiddle example here: http://jsfiddle.net/somekittens/70qebhbm/

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

Vue JS i18next: Handling Single Translation String Fallbacks

Recently, I've been utilizing i18next, and I decided to set a fallback value for some translated strings in case they are not available in the selected language. Here's an example: en: base.json "yes": "yes" "no": "no" fr: base.json ...

Issues with the animation of letters bouncing in css3

I wanted to implement an animated effect in CSS, specifically the "jumping letters" effect. However, it seems that the current implementation is not working as intended. The entire word moves upward instead of each letter bouncing individually. Can you h ...

Divide the page vertically. On the left side, feature an eye-catching image, while on the right side,

While I have a good understanding of bootstrap 5, I am currently working on a project that requires me to split the page down the center. However, I also need to incorporate a container in the middle that sets a boundary for the text so it doesn't exp ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

Building a multi-page application with ExtJs MVC

I'm new to MVC, especially when it comes to extJs. I want to implement the MVC approach in my project. I came across a tutorial at , which provided an example with only one page. In this example, they used app.js to load extjs views. My question is, w ...

When updating the content of a div with refreshed data using jQuery, it may result in displaying

Currently, I am utilizing a jQuery calendar plugin in my project. You can view its demo here. The issue arises when I attempt to refresh the data by clicking on the refresh button, resulting in duplicate values. To illustrate this problem, I have provided ...

Tips to successfully utilize addEventListener on a submit action

Having issues getting this to work on submit, it functions properly when using document.getElementById("gets").addEventListener("click", b_button); but does not work when I try document.getElementById("gets").addEventListener ...

Leveraging grunt-develop

I have recently developed a basic NodeJS + Express application that runs smoothly when I use the command node app.js. However, my current task is to incorporate grunt-develop into my project. Here is how I configured it: grunt.initConfig({ develop: { ...

What is the optimal approach for displaying numerous button components with varying values?

I've been developing a calculator in React and I decided to render all the buttons using the Button Panel component with what some might call a "brute force" method. return ( <> <div> <Button value="A/C" cl ...

Challenges faced with password hashing in Express.js

Can anyone assist me with the process of hashing passwords? I had a functional login/register feature on my express app until I integrated bcrypt. After registering a User, I can see that the password is hashed in the Database. However, when attempting to ...

Why do variables maintain the same value across modules when using the require function in Node.js?

We have a scenario where we have multiple files in the same directory: data.js var anArray = [1,2]; module.exports = anArray; mod1.js var data = require('./data'); module.exports = data; mod2.js var data = require('./data'); modul ...

Combining text and images in XSLT using CSS: A comprehensive guide

Greetings! I am facing a situation where I have an XML file containing image tags like this: <pb facs="ciao.jpg">. Additionally, I have an XSL file that includes a JavaScript snippet as shown below: <script type="text/javascript> function ...

Show an image when hovering over a dot using CSS - without hovering directly on the image

I'm currently working on a merchandising page that involves photoshopping several products onto a background image. I want customers to be able to hover over a dot positioned on each product to reveal its information and provide a link similar to . Ho ...

Tips on automatically focusing on an input within a Semantic UI React dropdown

I'm attempting to automatically focus on an input located within a Semantic UI React dropdown by using a ref, but unfortunately, it's not functioning as expected. The input should be focused when the dropdown is opened. Check out the code sandbox ...

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...

What is the reason for JavaScript consistently returning the initial value as the result?

My current issue involves customizing Joomla article content using a module. I am attempting to hide a div until a user clicks on an input, such as a radio button labeled Test1. Once Test1 is selected, another hidden field within the div should display the ...

Creating a Node.JS environment with Express and Socket.IO: A beginner's guide

Trying to set up a Node.JS server on port 3800 of my CentOS server and encountering difficulties: var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res){ res.send('&l ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

eliminate the offspring of a component (chessboard)

Hey there! I'm currently working on developing a chess game and I could really use your expertise to help me solve an issue. In my code, when I try to move a piece in the game, this is what happens: 1. First, I remove the existing piece from its cu ...

The use of callbacks is ineffective in addressing the asynchronous nature of

Hello everyone, I'm currently working on a weather app and I'm facing an issue with the asynchronous behavior of useState. I've come across some suggestions on Stack Overflow that using a callback in the useState function might solve the pro ...