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

Hide Scrollbar in CSS

Looking for a way to conceal the vertical scrollbar on my website, especially on mobile devices with touch scrolling capabilities. I attempted using CSS but didn't get satisfactory results, especially on older browser versions. ...

Tips for determining the duration between the Monday of last week and the Sunday of last week

Can anyone help me figure out how to retrieve the dates from last week's Monday to last week's Sunday using JavaScript? I've searched through various sources with no luck. Hoping someone here can provide some guidance. ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

Ways to refresh the appearance of clothing in Three.js

Currently, I am diving into the world of Three.js. My latest project involves adapting a shader that I originally created in Shader Toy to be displayed on my own webpage. The shader itself is a procedural terrain where users can navigate using the WASD key ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

Picture featuring a right-angled triangle on the right side

I have been experimenting with creating a complex image effect using CSS only, without any JavaScript. Despite several attempts, I haven't been able to achieve the desired outcome yet. CSS .container{ width: 500px; background-color: #0c2f45; ...

Why isn't the input appearing on the succeeding line below?

<label for="email2">Enter Your Email Address</label> <input type="text" name="email2" id="email2" placeholder="example: [email protected]"> <label for="phone2">Phone Number</label> <input type="text" name="phone2" id= ...

Maximizing the potential of HTML5 email input fields with jQuery validate

As I work on validating an <input type="email"> using the jQuery validate plugin, I am experiencing a small issue. The validation itself is working well, but after entering an incorrect value and receiving an error message, the error message remains ...

Enclose elements in a div using a jQuery each function

I have successfully parsed data from an XML feed to JSON, but now I want to wrap each part of the data within a div. Here is the code snippet I am working with: var newsDiv = $('<div class="news-feed">').appendTo($("body")); $(release ...

Duplicate the LI element in a way that it is inserted after the original LI instead of at the end

I am looking for a way to clone an item immediately after clicking on it instead of cloning it at the end of the list. Currently, it always clones to the END and adds it after the last LI in the list. Here is a link to the jsFiddle I created jsfiddle test ...

Instructions on displaying the main page even with just inputting the default directory in the URL

One scenario is when I input file:///C:/xampp/htdocs/At/html/ in the URL. My desired outcome is for file:///C:/xampp/htdocs/At/html/pages-login.php to be displayed instead. How can I achieve this? ...

Retrieving PHP variables within the HTML document of the current page

Suppose I have a page with a link <a href='edit_info.php?id=1001'>1001</a>. In the edit_info.php page, I want to use this id to query a database, like so: SELECT * FROM table WHERE id = $_GET['id'] Now, I need to populate ...

The ideal scenarios for employing functional setState

Lately, I've been delving into the world of React, immersing myself in tutorials and explanations on how to manipulate elements in different ways. One aspect that has caught my interest is the setState function, which allows you to update or override ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

Randomizer File Name Maker

I was questioning the behavior of Multer Filename. If Multer stores files with random filenames, is there a possibility of two files having the same name in Multer? In other words, if I am storing files from a large number of users, could the filenames e ...

What is the best way to include two parameters in an ajax call function in PHP?

I have developed a functionality for a variation table where users can choose sizes based on their selected color. Here is the variation table I created: |id | product_id | product_qty | product_colour | product_size |1 | 1 | 30 | red ...

Update the 'selected' text with the JQuery fnGetColumnData Plugin

I have implemented the fnGetColumnData plugin for filtering data tables, and it is functioning correctly. However, the dropdowns that appear are labeled "Select," and there are a total of five dropdowns. I would like to know how to change the text "Select" ...

Ways to confirm if a video has sound

There is a video that has an audio track, yet the volume is not zero or muted, resulting in the video being silent. I am looking for a way to determine if a video is audible so that I can perform specific functions accordingly. I came across a method to c ...

Angular routes are failing to update the view even after attempting to refresh

I am facing an issue while trying to develop an angular app where the child state is not loading properly. app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/"); $stateProvider .state('home& ...

The display: flex property is not being properly implemented in Tailwind CSS for the sm:flex

I have a div with the following styles <div class="hidden sm:visible sm:flex"> .... </div> The sm:visible style is applied like this @media (min-width: 640px) .sm\:visible { visibility: visible; } However, the property disp ...