Using Javascript to display elements with the kbd tag

I am interested in creating a function, possibly using Javascript, that can be embedded in HTML pages to display the function arguments enclosed in kbd tags with "+" as separators. This function should have the ability to accept any number of input arguments.

For instance, if I use fnRenderKBD(Ctrl+X, Y, Z), it should output Ctrl+X+Y+Z.

The key requirement is that this function must support a varying number of arguments.

Would it be feasible to develop such a function (and if so, how)? I have limited knowledge of JS.

Answer №1

My previous answer may not be the most optimal solution. A better approach could be to use the following code:

function renderKeys(element, keysToDisplay) {
    var separator = '';
    var content = null;
    for(var i = 0; i < keysToDisplay.length; i++) {
        var renderedKey = document.createElement('kbd');
        renderedKey = setText(renderedKey, keysToDisplay[i]);

        if (i > 0) {
            element.appendChild(document.createTextNode('+'));
        }

        element.appendChild(renderedKey);
    }
}

function setText(element, text) {
   if (element.textContent){
      element.textContent = text;
   } else {
      element.innerText = text;
   }

   return element;
}

(function() {
    var keys = [
        'Ctrl+X',
        'Y',
        'Z'
    ];

    var element = document.getElementById('display');

    renderKeys(element, keys);
}());​

Live Demo: http://jsfiddle.net/wPg7z/


You can also try this alternative approach:

function renderKeys(element, keysToDisplay)
{
    var separator = '';
    var content = '';
    for(var i = 0; i < keysToDisplay.length; i++) {
        content += separator + '<kbd>' + keysToDisplay[i] + '</kbd>';
        separator = '+';
    }

    element.innerHTML = content;
}

(function() {
    var keys = [
        'Ctrl+X',
        'Y',
        'Z'
    ];

    var element = document.getElementById('display');

    renderKeys(element, keys);
})();
​

Live Demo: http://jsfiddle.net/gTYxP/1/

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

Implementing dynamic classes for each level of ul li using JavaScript

Can anyone help me achieve the goal of assigning different classes to each ul li element in vanilla Javascript? I have attempted a solution using jQuery, but I need it done without using any libraries. Any assistance would be greatly appreciated! con ...

Can you explain the significance of argument[0] in JavascriptExecutor?

I recently implemented the "How to handle hidden web elements using the JavaScript executor method". However, I am still unclear about how the method works. public static void selectDateByJS(WebDriver driver, WebElement element, String dateVal) { Javas ...

Converting PHP JSON encode to an Ajax array proved to be quite challenging for me at first, as it was a new concept to

Managing Students Data public function retrieveStudentsInformation() { $studentsData = $this->member->getStudentsPosts(); $formattedStudents = array(); for($i=0; $i<count($studentsData); $i++) { $formattedStudents[$i][&a ...

Is there a way to access a JSON node dynamically without relying on the eval function?

Path variables can be unpredictable, ranging from just a to a/b, and even a/b/c. My goal is to dynamically reach a node based on the path provided. The code snippet below achieves this, but I am open to exploring alternative methods that do not involve usi ...

Can I customize the color of an SVG image with CSS (jQuery SVG image substitution)?

This is my innovative solution for easily embedding and styling SVG images using CSS. Traditionally, accessing and manipulating SVG elements with CSS has been a challenge without the use of complex JS frameworks. My method simplifies this process, making ...

Type Error in Node.js Form Submission: Unable to define 'userId' property due to undefined value

After implementing login and registration features on a specific page in my application at views/employee/login.hbs, I encountered an issue. Upon entering registration details (email, username, password, and confirm password) and clicking the register butt ...

What sets apart an anonymous function from the => notation in node.js?

I was exploring how to read a file using node.js. Previously, I would use this code snippet: fs.readFile('/etc/passwd', function(err, data) { if (err) throw err; console.log(data); }); Node.js’s official documentation showcases the follo ...

Modify content for slideToggle

Check out this jfiddle link: http://jsfiddle.net/RHbzv/ I'm attempting to change the text from 'See more' to 'See less' when displaying the answer, but I can't seem to make it work. Here's what I've tried: $(&ap ...

Access Vue.js data attribute in jQuery

Is there a way to extract the data-src attribute value from the following HTML code using Vue.js? <img id="some_id" :data-src = "some_path"> I attempted to assign this value to a variable using jQuery: var imgSrc = $("img:data(src)"); Unfortunat ...

Framework7 initialization not triggering when page is initialized

Unable to get init function working in my Framework 7 app. I have attempted all the solutions provided in the following link: Framework7 Page Init Event Not Firing // Setting up Application var myApp = new Framework7({ animateNavBackIcon: true, ...

Tips for hiding website content on larger screens

Is there a way to hide website content on screen sizes over 1600px and display only a message image instead? ...

Ways to send users to a different page with parameters without relying on cookies

Is there a way to redirect users from URLs containing parameters like /?v=xxx to the index page without those parameters showing in the address bar? I still need to retain and use these parameters internally. One approach I considered was using custom hea ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

Trouble arises as the Raspberry Pi GPIO pins refuse to toggle

Encountering an intriguing issue here. I've developed a Python program to regulate the climate of a room with a web interface. While the program functions properly, upon restarting the Raspberry Pi, all GPIO pins are activated. It's only after ac ...

Can a JavaScript function be handed to a constructor for an event handler?

The JavaScript function provided: function ShowFax() { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "WebServices/SendFaxService.asmx/SaveFaxData", data: "{}", dataType: "json", ...

Leveraging the Power of SASS Variables Across Your Entire NativeScript Application

Currently, I am in the process of developing an app using NativeScript 6.4.1 along with Angular 8. In order to enhance my styling capabilities, I have decided to incorporate SASS due to its advantageous features like variable names. My designer has suppli ...

The page's layout becomes disrupted when the back end is activated, requiring some time to realign all controls

I recently set up a website and I am facing an issue where certain pages shake uncontrollably when buttons are clicked. The problematic page can be found at the following link: Specifically, when trying to click on the "SEND OFFER" button, the entire pag ...

Struggling with Enum Field Implementation in Mongoose Schema

Issue with Mongoose Enum Field Validation const userSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please provide your name!'] }, email: { type: String, required: [true, 'Please enter your email ad ...

What is the best way to vertically align a div in the center?

Similar Question: What is the Optimal Method for Vertically Centering a Div with CSS? .title_text_only{ position:absolute; width:100%; display:none; z-index:9; top:50%; bottom:50%; text-align:center; color:#fff; font-size:18px; text-shadow: 1px 1p ...

Leveraging personalized services prior to initializing the AngularJS application

I am attempting to utilize custom services prior to the application's initialization. var initInjector = angular.injector(['ng', 'myModule']); var myCustomService = initInjector.get('myCustomService'); var $http = init ...