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

The inheritance caused this scope to be lost

Here is an illustration of code with two files and "classes". In the CRUD class, there is a problem with this.modelName when setting routes as it changes the context. The question arises on how to maintain the same scope within the CRUD where modelName is ...

Error handling in Mongoose callback functions

Currently, I am delving into nodejs, express and mongoose. A question has arisen in my mind regarding the findOne function used to fetch a document from the database. Typically, it is utilized like this: Product.findOne({_id: req.params.id},function(erro ...

Is it possible to create rounded or curved top corners for a box using HTML?

I'm looking to create a card with rounded top corners and wondering if there is a way to achieve this. Currently, here is the code I have: <div id="card1"> <div id="card1i"></div> </div& ...

Utilizing the .data() method for establishing a variable

I am facing an issue while trying to set a variable in a form using .data(). The problem is that I cannot see any output for the variable "fee" - it just appears blank. What I am trying to achieve is for the user to select a Type, enter a footage, and then ...

Stopping background content from scrolling while using position: fixed

Is there a way to prevent content from scrolling behind a fixed position element? Check out the demo here .navbar-default { background-color: #4c68f9; margin-bottom: 0; border: none; } .navbar-default.affix { background-color: #4762ed; margin ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Issue with Translate3d functionality in fullpage.js not functioning as expected

Currently, I am in the process of constructing a website using fullpage.js with WordPress. Everything is functioning well except for one issue - when attempting to disable the plugin by using destroy() or changing setAutoScrolling to false, the translate3d ...

Exploring the options for accepting various file formats with Swal SweetAlert

Currently, I am using Swal Sweet Alert within my Vue.js application. I have successfully implemented code to allow image files, but now I am seeking assistance on how to extend this functionality to include multiple file types such as PDFs, PPTs, and Doc ...

Why is the AJAX request not functioning properly after using jQuery's hide method?

It seems that the first AJAX call works fine when I hide the div, but subsequent requests are not going through. a) Clicking on the signup button triggers an AJAX request to display the details. b) Pressing the hide button hides everything within that di ...

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...

Troubleshooting Dynamic Input Issue - Incorrect Appending Behaviour - Image Attached

I am working on a project that involves adding input fields dynamically using JavaScript. However, I've encountered an issue where the styling of the first input field is not applied correctly when it is clicked for the first time. You can see the dif ...

Guide on how to beautify HTML and generate output files in the identical directory as the current one

Hey there! I'm currently working as a junior front-end developer and have recently delved into using gulp. One of the challenges I face is dealing with HTML files received from senior developers that aren't well-formatted, containing excessive wh ...

Is there a way to determine if a JavaScript method is compatible with my current Node.js version?

Looking to implement the reduce() method in my Node.js application, but I'm unsure if it's compatible with my current version 4.2.6. Is there a way to safely determine if I can use this method without causing any issues? Appreciate any help on t ...

Switch over to using a for loop

I have a query regarding implementing multiple toggles within a for loop. For instance, I want a toggle menu to appear when clicking on a div. Here is the code snippet: for (var i = 0; i < myObjectString.length; i++) { var obj = JSON.parse(myObjectStr ...

The initial dropdown menu in PHP coupled with Javascript fails to retain my chosen option

As a novice PHP programmer, I successfully created a double drop-down list from a MySQL database. The idea is to choose a claims hub in the first box and then select an attorney associated with that specific hub in the second box. However, I am facing an ...

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

What benefits does utilizing Microsoft Workflow Foundations offer?

I am currently working with an investor who is pushing for us to utilize Microsoft Work Flow Foundations for our workflow and database. However, I have already created an interactive graph-database using Javascript, Node.Js, and ArangoDB that perfectly su ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Having trouble setting cookies with Node.js Express?

Check out this code snippet: const app = express(); const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.post("/pinfo", (req, res) => { var form = new formidable.IncomingForm(); form.parse(req, async functi ...