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

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 ...

Is there a way to programmatically simulate clicking on the "Cancel search" button?

I have a text input field with type "search". In order to perform UI testing, I need to simulate clicking on the "cancel search" button: The code for this specific input field is as follows: <input type="search" value="user"> Although the cancel b ...

Calculate the total count of responses within the JSON data returned

Hello all, I need some guidance on calculating the total number of responses in a JSON response that adhere to a specific rule using JavaScript. Here is the JSON response that I am discussing: [ { "InvoiceNumber":"INV0319", "InvoiceOrd ...

Using CSS transform to enhance Flash content

I am currently working on a web application that is contained within an iframe. The iframe has been scaled using -webkit-transform:scale(0.8), which is functioning well. However, I am encountering an issue with the flash audio recorder within the iframe no ...

Is it possible to align items in flexbox to a specific baseline?

Is it possible to specify a baseline override when utilizing flexbox and trying to use align-items:baseline? I have a flex container that contains various divs such as title, image, body, and description. For these flex items, I want them to be centered ...

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

Ensure that images are not displayed until fully loaded by utilizing the jQuery .load() function following the completion of Ajax

I have been using the ajaxify-html5.js script from this repository and it has been working flawlessly. However, I noticed that during the content loading process (especially around line 145: $content.html(contentHtml).ajaxify();), there is a brief moment w ...

Having trouble with a jquery link not working even after removing the 'disabled' class

I am currently using a script that disables links with the class "disabled" //disable links $(document).ready(function() { $(".disabled a").click(function() { return false; }); }); In addition, I have another script that toggles the disabled s ...

Radio buttons have been concealed and are not visible

Tried the solutions recommended in a previous question about radio buttons not showing in Safari and Chrome, but unfortunately, it did not solve my problem. It seems like this issue is different from the one discussed in that question. The WordPress them ...

Tips for displaying a Bootstrap 5 popover triggered by a select option change event

I'm using a select box with 4 options, and I have set it up so that when the user clicks on one of the options, a Bootstrap 5 popover is triggered dynamically upon the change event. Fiddle: https://jsfiddle.net/mayursutariya93/qjeg5r9b/6/ Here' ...

Creating JOIN tables within the create action involves assigning related ids to each table

I am currently working on a room reservation system that involves including options for each room. Data related to the options and their join table, reservation_options, are successfully inserted into the params. However, I am facing an issue with assignin ...

Is there a method to prompt the browser to retain form data when using the back button?

Having a puzzling problem. I've developed a sophisticated quote form for our company that utilizes ajax to display prices for products based on user input. There are 6 hidden fields set up as follows: productname1 productname2 productname3 and the ...

Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript. Currently, I am faced with the challenge of having to create separate div elements each time I want to add n ...

Modify the image inside a div when hovering

How can I create a product card that displays thumbnails of images when hovered over, and changes the main image to the thumbnail image? My current challenge is getting this functionality to work individually for each card on an e-commerce site. Currently, ...

How to make background image fade in with jQuery on hover

I want to create a row of menu buttons with transparent background-images that fade in on hover. Is it possible to achieve this effect using jQuery? Check out an example here! ...

Display only the div on an iPad screen

Is there a way to show this DIV only on an iPad screen? I've looked around on Google for solutions, but none of them seem to work. It always ends up displaying on my computer as well. Is it possible to make it show only on an iPad screen? @media only ...

Adjust the fade-in effect to transition from a white hue to a custom color

Is there a way to customize the color of the fadeIn() effect from its default white to a specific color? For example, when transitioning the entire webpage fades in from grey and fades out to grey when a link is clicked. Here is my current code snippet: ...

I updated the color of my a:link using jQuery, but now my a:hover is not functioning as expected

Due to the readability issues of the navigation color against a specific image, I am looking to modify it for a particular page. Below is the HTML code: <div id='nav'> <ul> <li id='navBiog'> ...

"Ensuring Consistency: Addressing the Conflict between CSS and Font

I'm encountering a "mixed content" error on my website caused by one font being loaded via HTTP. The font is referenced in a CSS file like this: @font-face { font-family: 'fontXYZ'; src: url('../font/fontXYZ.eot'); src: url ...

Transferring information from an HTML page to a PHP script

I am facing a dilemma with my current PHP script that is called from an HTML link. The setup requires the script to accept non-user input from the page, specifically static data already present. The line calling the script appears like this. <div class ...