I'm feeling lost trying to figure out how to recycle this JavaScript function

Having an issue with a function that registers buttons above a textarea to insert bbcode. It works well when there's only one editor on a page, but problems arise with multiple editors.

Visit this example for reference: http://codepen.io/anon/pen/JWOzZj

In the example, you'll notice that the buttons in the second editor work fine, while those in the first do not and seem to overwrite everything into the last editor created.

Since I'm not proficient in JS, I'm hopeful it's a simple fix to make it reusable.

Below is the provided JS code:

/*
 * Forked from Octus Editor: https://github.com/julianrichen/octus-editor MIT license
 */
function OctusEditor(editor_id) 
{
    var editor_bar = 'bar_' + editor_id;
    var this_editor = document.getElementById(editor_id);
    /*
     * init()
     *
     * Start editor
     */
    function init() 
    {
        var quotes  = document.querySelectorAll('[data-quote]');

        // Register tags
        registerElements(editor_bar);

        // Register all possible quotes.
        for (var x = 0; x < quotes.length; x++) 
        {
            quotes[x].addEventListener("click", registerQuote, false);
        }
    }

    /*
     * registerElements()
     *
     * Register all tags from each editor
     */
    function registerElements(id) 
    {
        // Get all styles
        var tags    = document.querySelectorAll('#' + editor_bar + ' .styles ul li[data-tag]'),
            snippet = document.querySelectorAll('#' + editor_bar + ' .styles ul li[data-snippet]');
        // register all the tags
        for (var i = 0; i < tags.length; i++) 
        {
            // Log editor id
            tags[i].editor_id = id;
            // Add click event
            tags[i].addEventListener("click", registerTag, false);
        }

        // register all the snippets
        for (var x = 0; x < snippet.length; x++) 
        {
            // Log editor id
            snippet[x].editor_id = id;
            // Add click event
            snippet[x].addEventListener("click", registerSnippet, false);
        }
    }

    /* More of the JS code continues... */

And here's the HTML code related to the form:

<script type="text/javascript">
window.onload = function() {
    OctusEditor('test');
};
</script>
    <div id="bar_test" class="octus-editor group">
            <div class="styles group">
                <ul>
                <li data-tag="b" class="bold" accesskey="B">B</li>
                <li data-tag="i" class="italic" accesskey="I">I</li>
                <li data-tag="u" class="underline" accesskey="U">U</li>
                <li data-tag="s" class="strike">S</li>
                </ul>
                <ul>
                <li data-tag="img">img</li>
                <li data-tag="url">url</li>
                </ul>
                <ul>
                <li data-tag="code">code</li>
                <li data-tag="quote">quote</li>
                <li data-tag="spoiler">spoiler</li>
                </ul>
        </div>
            <div class="textarea group">
                <textarea name="{:name}" rows="3" cols="17" id="test"></textarea>
            </div>
    </div>

Answer №1

Merge your onload functions together:

window.onload = function() {
    OctusEditor('test');
    OctusEditor('test2');
};

Check out the code on CodePen

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

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

At what point does the browser begin fetching the background images specified in a stylesheet?

Are images mentioned in a valid CSS declaration with a background-image value downloaded when the stylesheet is parsed or when the declaration is applied on a page? In simpler terms, do I need to download all background images listed in my stylesheet even ...

Is it possible to access forms and input fields in an AngularJS script without having to pass them from the HTML code?

Seeking a solution for input field validation, I have written code where input field states are passed from HTML to a script through a function. However, my goal is to directly retrieve the values in the script without passing them from the HTML when calli ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

Determine the central x and y coordinates of elements depending on the specified screen dimensions

Is it possible to determine the center position of an element at a specific screen size using jQuery? I am looking to calculate the center position of an element based on provided height and width dimensions. For instance, if I provide the screen size (1 ...

Navigating Angular's Credit Card Input Functionality

I am looking to limit the input capacity to 16 numbers and add a space between each set of 4 numbers. After conducting an extensive search for a credit card input that allows users to enter 16 digits with a " - " or space in between, all results were for ...

Display/Conceal WP Submenu

Struggling to switch the behavior of my Wordpress menu. Want it to display when clicked, not when hovered: <nav> <ul> <li> <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ...

Is there a way for me to update the placeholder text in my script from "CHANGE ME

Can anyone help me troubleshoot this code that's not working on my computer? I have a paragraph with the text CHANGE ME inside an element with the id "warning". I want to update this text when the login button is clicked, but it doesn't seem to ...

What is the correct way to iterate through an object, evaluate three properties, and then push them into an array?

I am tasked with creating a function called runOnRange that will populate a new array based on the properties of an object. The object contains three properties: start, end, and step. The goal is to push specific numbers into the array according to these p ...

Error: Browserify jQuery Plugin Not Working

Having trouble browserifying a jQuery plugin and keep seeing this error in the browsers console: Uncaught Error: Cannot find module 'jquery' Here's how I have my package.json set up: "browserify": { "transform": [ "browserify-shim" ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

Accessing getUserMedia within Internet Explorer 11 or utilizing MediaStream on IE 11

I am attempting to utilize the getUserMedia function in IE 11 with the help of the temasys plugin. However, IE does not support the MediaStream instance returned by getUserMedia. Below is a snippet of my code: import React from 'react' import { ...

delay of Paypal API disbursement for transactions with a range of money values

After browsing through various resources such as this link, that link, and another one on the PayPal developer website, I attempted to implement a payment processing system that allows users to approve a preset amount of money. Similar to services like Ube ...

What steps should I take to develop an Outlook add-in that displays read receipts for action items in sent emails?

Currently, I am in the process of developing an add-in that will enable me to track email activity using a tool called lead-boxer (). With this add-in, I am able to retrieve detailed information about users who have opened my emails by sending them with an ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

"Exploring the interactivity of touch events on JavaScript

Hi there, I'm currently facing an issue with the touch events on my canvas. While the mouse events are functioning correctly and drawing as expected, incorporating touch events seems to be causing a problem. When I touch the canvas, the output remains ...

Incorporate Bookmarklet into GitHub README.md

Trying to add a Bookmarklet to a Github README.md, but encountering issues with the markdown code: [Bookmarklet](javascript:alert('not-working')) It appears that the javascript in the link is being stripped out from the compiled output. Is this ...