How can I use JQuery to sum up the numbers within div elements?

Is there a way to automatically number the generated blocks? For example, the first block would display "1", the second "2" and so on. Below is my current code. Simply input the desired number of blocks in the input field.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Traversing and Element Creation</title>
</head>
<body>
    <h1>Traversing and Element Creation</h1>
    <p>Number of divs to generate:
    <input id="numberInput" type="text" name="inputField" style=width:200px;>
    <input id="numberButton" type="button" onclick="BLOCKGENERATOR_APP.init();" value="Generate">
    </p>
    <section id="blockSection"></section>


    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script>


        // App-module pattern for main function
        var BLOCKGENERATOR_APP = {
            $blockSection: null,    //Divs
            blocks: null,           //Array

            init: function(){       //init
                var BG = BLOCKGENERATOR_APP;    //Shortens the code further
                var setSection = function(){    //Sets functions to html-section with id "blockSection"
                    BG.$blockSection = $("#blockSection");
                }();
                
                var spawnInput = function(){     //Initialize function for spawning the divs
                    var input = document.getElementById("numberInput").value;
                    BG.blocks = generator.fetchBlocks("div", input);                  
                    BG.$blockSection.append(BG.blocks);
                }();

                var setEvents = function(){         // Functions for div-interaction
                    $("div", BG.$blockSection).on("mouseenter", function() {    // When mouse touch div, the opacity renders to 1
                        $(this).animate({
                         opacity: 1.0   
                            }, 2000, function() {});                            // Set 2 sec transition time
                    });
                    
                    $("div", BG.$blockSection).on("click", function() {     // On click, color of targetet div will be changed to MediumOrchid
                        $(this).css("background-color", "MediumOrchid");
                    });
                    
                    $("div", BG.$blockSection).on("dblclick", function() {  // On double-click, color of targetet div will be changed to yellow
                        $(this).css("background-color", "yellow");
                    });
                }();
            }//--end init
        };//--end BLOCKGENERATIR_APP


        // Function for generating divs \\
        var generator = (function(){                    
            var fetchBlocks = function(tag, input){
                var blocks = [];                        // Array of generated divs
                for(var i = 0; i < input; i++){         // Generates until input value is met
                    var $newBlock = $("<" + tag + ">")  //
                        .css(                           // Alters css properities of divs
                            {
                                "width": "80px",
                                "height": "80px",
                                "margin": "10px",
                                "background-color": "Red",
                                "float": "left",
                                "opacity": "0.5"        // Initial amount that's altered during event
                            }
                        );
                    $newBlock.text(i+1);               // Add numbered text to new block
                    blocks.push($newBlock);             // Adds instance of block to array
                }
                return blocks;                          // Returns array
            }//--end fetchBlocks
            
            return {fetchBlocks: fetchBlocks}           // Returns the blocks
        }());//--end generator
    </script>
</body>
</html>

Answer №1

.text(i); Make sure to include this line after styling the dynamically generated tags in your generator function.

Here is an example:

var $newBlock = $("<" + tag + ">").css({
        "width": "80px",
        "height": "80px",
        "margin": "10px",
        "background-color": "Red",
        "float": "left",
        "opacity": "0.5"
    }).text(i);

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 diverse color gradients to individual vertices within a geometry using three.js

My goal is to enhance the functionality of this code snippet so that when the button is clicked, the selected mesh's neighborhood vertex is highlighted with a gradient effect. function addSphere() { var position = new Array(); var notAboveGround = tr ...

Is it necessary to use Hapi.js on the client side in order to establish a websocket connection using the Hapi.js protocol?

Currently, I am in the process of developing an API using Hapi and requiring WebSocket functionality. After some research, it appears that Nes is the preferred choice to integrate with Hapi for this purpose. Fortunately, Nes simplifies the process signific ...

After transitioning my Image Modal from an ID to a Class, it appears to not be functioning properly

I recently implemented an image modal on my website using the ID attribute, but it didn't seem to work as expected. After changing the id to a class, now the image modal is not functioning at all and I'm struggling to figure out what went wrong. ...

Performing an Ajax request in Django

Currently using Django and have created a delete button function. It's working perfectly for the /employer/job/edit URL, but encountering issues with the vendor/job/edit URL. The template is shared between these two places and my code works for one bu ...

Is it possible to set data using a React Hooks' setter before the component is rendered?

Instead of making a real API call, I am exporting a JS object named Products to this file to use as mock data during the development and testing phase. My goal is to assign the state of the function to this object, but modified with mapping. The current st ...

Sorting items in jQuery by height

Currently, I have a jQuery sortable set up based on a list structure: <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul> To ensure consistency in the appearance o ...

What could be causing the disappearance of the replaced div content after a refresh?

Does anyone have experience with using jquery in conjunction with django? I am currently trying to update the content of a div after successful user authentication. While my code is functional, I'm facing an issue where upon page refresh, it reverts b ...

Enhancing a variable's value while simultaneously boosting its rate of increase through Javascript

Looking to adjust the timing on a number increase function using setInterval(Function, time). Initially set the variable for time as time = 1000, but now looking to dynamically change it by implementing a function triggered by a button click: function cha ...

When using my webrtc technology, I configure my sdp to establish a recvonly direction

While attempting to make a video call using WebRTC, I encountered bugs during testing. My goal is to integrate this project into a webview for my Android app. I conducted testing using phone-pc and phone-phone scenarios. Scenario A: When the PC initialize ...

Comparing `$(window).scroll(fn)` with `$("html,body").scroll(fn)` shows the different ways to

My go-to method for getting or setting the scroll offset in a cross-browser way is: $(window).scrollTop() as a getter, and $('html,body').scrollTop(offset) as a setter. However, I'm unsure about the proper approach for handling the scroll e ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

Tips for executing several JavaScript files using the Node.js command line?

I am looking to launch 4 scripts using Node.js. myapp -script1.js -script2.js -script3.js -app.js -package.json .... .... I attempted to run them with the following commands: node script1.js && node script2.js && node scrip ...

Stylesheets per module in Angular 2

For my website design, I've decided to adopt a modular structure using sass. To ensure consistency throughout the module, instead of defining stylesheets at the component level, I plan to define them at the module level and import them into each compo ...

Resolving the issue of the 'Failed to load resource: net::ERR_FILE_NOT_FOUND' error

I'm encountering issues with loading my CSS in different browsers when using the "Copy Path" feature in VSCode. While everything displays correctly in preview mode within VS, none of the styles appear when pasting the path into Chrome or Edge. Below ...

Is there a way to remove the excess white space beneath my content without resorting to using overflow-y: hidden?

I am struggling to eliminate the excess white space below the body of my web page in order to make it fit perfectly within the view of a web browser. Adding height helps with vertical alignment but leaves unwanted white space. I need a solution that doesn ...

Guide on using Python to save a legitimate HTML page of a YouTube video

When I use requests.get(URL, allow_redirects=True) on websites like Youtube or Reddit, instead of seeing the usual HTML text content that appears when I view the page in a browser, I get a bunch of unexecuted JavaScript. All I really need is the title of ...

Why is it that I am not receiving JSON data in my Angular application?

I am currently working on a class within a webapi public class ResponseObject { public int Success { get; set; } public string Message { get; set; } public object Data { get; set; } } Within my ASP.NetCore, I have the following method: publi ...

Ways to differentiate between a single date and multiple dates using PHP

Is there a way to compare two dates in PHP? I have two different dates: one is from the database and the other is selected from a Datepicker. $dbdate = 01-06-201402-06-201403-04-201405-06-2014 //DB date $datepickerDate = 06-06-2014 //Datepicker date. ...

Switch navigation - always display the menu on the existing page

I have a toggle menu implemented. Please check out the code and functionality on JsFiddle When clicking on a h3 tag like Category 1 (which is an a tag), the menu opens and remains open on the current page. However, if you click on the h3 tag (Category1) ...

Utilizing jQuery to Trigger a Click Event on an Element Without a Class

What is the best way to ensure that the "click" event will only be triggered by an href element unless it does not have the "disablelink" class? Avoid processing the following: <a class="iconGear download disablelink" href="#">Download</a> P ...