What is the best way to retrieve the unique identifier of dynamically created divs and showcase a message based on that identifier?

Is it possible to retrieve the id of a dynamically generated div and show a unique message when each div is clicked in the code snippet found at this link?

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

var columns = 10, container = $("#container"), width = (100 / columns);

$("head").append("<style>.col { width: " + width + "%;} .row {  height: " + width + "%  }</style>");

for(var ii = 0; ii < columns; ii++) {
    container.append("<div class=\"row\" />");
    row = $("#container > div:last-child");

    for(var i = 0; i < columns; i++) {

       row.append("<div class=\"col\" style=\"background: " + get_random_color() + "\">szin</div>");

    }
}

Answer №1

Avoid using the onclick attribute in your HTML code as it is unrelated to layout and appearance. The best practice is to keep functionality in JavaScript. Instead, create an ID scheme using iterators and set up a click handler for better organization.

Check out this example on http://jsfiddle.net/YYh3w/. Additionally, I've optimized your element generation for improved readability. jQuery simplifies the process of creating dynamic elements effortlessly.

var columns = 12,
    container = $("#container"),
    width = (100 / columns);

$("head").append("<style>.col { width: " + width + "%;} .row { height: " + width + "% }</style>");

for (var ii = 0; ii < columns; ii++) {
    var $row = $("<div />", {
        class: "row"
    });
    container.append($row);

    for (var i = 0; i < columns; i++) {
        var $col = $("<div />", {
            class: "col",
            style: "background: " + get_random_color() + ";",
            html: "example",
            id : ii + "-" + i
        });
        $row.append($col);
    }
}

$("div.col").click(function () {
    alert(this.id + " " + $(this).html());
});

Answer №2

Discover the power of dynamic ids! Simply use this code snippet to generate unique IDs for your div elements. When you click on any div, an alert will display the id of that specific div:

row.append("<div id=\"div_" + ii + "_" + i + "\" onclick=\"alert(this.id)\" class=\"col\" style=\"background: " + get_random_color() + "\">sample</div>");

Check out the live demo on JSFiddle: http://jsfiddle.net/FJhDw/5/

Answer №3

If you want to specify a div, it is important to give each div an id and you can also run a javascript function on each div when it is created.

For example, if you need the id of a div when clicked, you can add an onclick attribute to the div and pass it to a function.

Check out this Demo

updated: Demo 2

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

When hovering over a hyperlink, an image appears but I want to adjust the image's position in relation to each link

I have a unique feature on my website where text hyperlinks reveal small thumbnail images when hovered over. This concept was inspired by an example I found on this page. I initially implemented the code from a post on Stack Overflow titled Display Image O ...

The application of CSS transition fails in the context where top property is set as auto

I have been exploring an online tutorial that almost met my requirements. However, I encountered a challenge with the CSS 'transitions' effects. Basically, I need the text to be positioned at a specific distance from the top because the title wi ...

iOS 8 requires the use of a numeric keyboard for entering passwords

Is there a way to ensure that iOS displays a numeric keyboard for my password field? Currently, I am utilizing the following code: <input type="password" pattern="\d*" name="pass"/> This method was effective in iOS7, however, it seems that the ...

Implement a counter in a JavaScript table, initializing it to zero

I have successfully written my code, but there is one issue. The first row is starting with the number one instead of zero. I'm looking for suggestions on how to start from zero. Any help would be greatly appreciated. Thanks! <script> var tabl ...

Incorporate jQuery into the layout in CakePHP version 3.4

I recently started incorporating libraries such as jQuery and Twitter Bootstrap using composer. Now, I am trying to include the jquery.min.js file from /vendor/components/jquery/ in my /src/Template/Layout/default.ctp. However, I have encountered an issue ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

Enhancing CSS with Additional Properties

As a web developer, I recently had the opportunity to explore the new LOGIN PAGE preview of GMAIL and was very impressed with the Sign In button's UI. After examining the Page's CSS, I discovered some interesting properties, such as: **backgroun ...

A guide on using jQuery to cycle through every row of every table on an HTML page

I am trying to figure out the correct syntax for nesting two loops within each other in jQuery. The first loop should iterate over each table in an HTML page that does not have any IDs or classes, while the second loop should go through each table row of t ...

"We encountered an error with the external script while trying to load file content using jQuery's ajax function. It

//C.php <script type="text/javascript"> $(document).ready(function(e) { $('div').load("D.php"); }); </script> <div></div> //D.php <script type="text/javascript" src="D.js"></script> //D.js console.log(45 ...

Bracketing the Webpage: A Display of Unique Design

Currently, I am utilizing the Brackets code editor to create a webpage in HTML format. My aim is to transfer these files to another computer so that the user on that device can view the webpage created from these HTML files. Strangely, when I open the HTML ...

Verifying if a particular track is currently playing in the HowlerJS playlist

I am currently experimenting with a HowlerJS playlist code and would like to create a button that can detect if a specific song in the playlist is playing. When this button is clicked, I want it to hide a certain line of text. However, my knowledge on this ...

printing not displaying colors

Is there a way to maintain the colors while printing my HTML page to PDF? <table class="table table-responsive table-striped"> <thead> <tr> <th>Elev</th> <th>Session n ...

I need some assistance, please. Can someone explain why the Bootstrap card is staying aligned to the left in mobile view

I've tried everything, but it's still not working. Can anyone help me out? Here are some photos. BEFORE AFTER When I view the card on mobile, I want it to stay centered. Could there be some missing code that I'm overlooking? I would great ...

I've encountered an issue with adjusting certain property values for an SVG component within my React project

I'm experiencing an issue where the pointer property is working, but the fill property isn't having any effect. When I inspect the elements in the browser console, I can manually change the element.style to affect the styling of the SVG component ...

Hide additional tabs on the page when the width of the tabs exceeds the page width

I am currently working on a Google module tab application. I have successfully added the tab control with drag and drop functionality within a specific area. However, I now need to limit the number of tabs displayed on the page. Regardless of the total cou ...

Detecting the click area within a window using JavaScript to automatically close an element

Hello everyone, I am currently working on implementing a JavaScript code that is commonly used to detect click areas for closing an element such as a side navigation or a floating division when the user clicks outside of the element. The functionality wo ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

The grid layout is being disrupted by a concealed input

As I work on styling my admin panels with Twitter Bootstrap, I've encountered a strange issue. Upon testing in Chrome 28 and Firefox, adding a simple hidden input seems to disrupt the grid layout. If the hidden input is moved into div.span6 or remove ...

Ajax request missing Github Basic OAuth token in authentication process

My personal access token is not being passed to the request when I make an ajax call. I keep receiving an error message saying API rate limit exceeded for 94.143.188.0. (But here's the good news: Authenticated requests get a higher rate limit.. I atte ...

Associate a click event to a dropdown menu element to trigger on selection

My issue involves having multiple select elements. When one of them is changed, I am trying to bind a click event only to its next element with the .btn class. Below is the code snippet illustrating my problem: <div class="whole"> <ul> ...