Tips for adding a click event to a random "div" within a parent "div" element?

Upon clicking a main "Div", it splits into an n X n matrix with random colored divs. I now want to implement a click function for these random colorful divs that are scattered throughout the main "div".

$(window).load(function() {
  var no = 1,
    $m = $(".main_div"),
    size = 200;

  $m.live('click', function() {
    no++;
    var n = no * no,
      i, _size;
    $m.empty();
    for (i = 0; i < n; i++)
      $m.append($('<div title=' + i + '/>'));
    _size = size / no;
    $m.find('> div').css({
      width: _size,
      height: _size
    });

    var colors = ["#FFFFFF", "#CC00CC", "#CC6699", "#0099CC", "#FF99FF"];
    var rand = Math.floor(Math.random() * colors.length),
      randomTotalbox = Math.floor(Math.random() * $('.main_div div').length);
    $m.find("div:eq(" + randomTotalbox + ")").css("background-color", colors[rand]);
    var rand = Math.floor(Math.random() * colors.length);
  });
});
  .main_div {
    width: 200px;
    height: 200px;
    background-color: #9F0;
  }
  .main_div > div {
    float: left;
    box-shadow: 0 0 1px #000;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_div" id="demo">

</div>

Check out the demo here.

Answer №1

It seems like the clickable div is dynamically added to the DOM when you click on a button.

This implies that these divs were not present initially, allowing you to utilize

Babak Naffas' solution along with the .delegate method

Here's an example:

$('body').delegate('.main_div > div','click',function(){
  // Add your instructions here
});

For further information, refer to: Exploring the differences between jQuery's .click() and .on("click") methods

Answer №2

If you want a certain action to occur when the NxN <div> elements within the matrix are clicked, you can use the following code snippet:

 $(".main_div > div").on('click', function (evt) { ... } );

This code will bind the specified function (the 2nd parameter) to the click event of the <div> elements in the matrix, similar to how it is done with the CSS class defined by the selector.

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

Tips for triggering an ajax error using ASP.NET MVC3

I am looking to manage all server-side errors using jQuery on the client side. To achieve this, I have created an exception handling attribute for my MVC3 application like the following: public class JsonErrorHandlerAttribute : HandleErrorAttribute { ...

Tips for positioning bootstrap-vue dropdown button items evenly

Can anyone help me align the dropdown button child items horizontally? I've tried customizing it with CSS but no luck. The control link can be found here Check out a sample on Js Fiddle here This is how I expect the design to look like: https://i.s ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

The checkbox's value is initially set to 1 when it is checked for the first time, and remains unchanged

When the checkbox value is set to 1 and then unchecked, it still retains the same value. I used Firebug to inspect the code. Here is the code snippet: <?php $form=$this->beginWidget('CActiveForm', array( 'action'=>Yii::app()- ...

Best locations for placing files when integrating Javascript into Wordpress

I have been struggling to make JavaScript work and determine the correct location to place the files. After attempting various methods, I am now wondering what the most logical approach would be. Despite spending a week on this task, the lack of a tutoria ...

What is the best approach to transforming my jQuery function into CSS to ensure responsiveness?

I have created a jQuery animation with four functions named ani1(), ani2(), ani3(), and ani4(). Everything is working fine on desktop, but now I am facing the challenge of making it responsive for mobile devices. I am looking for CSS code to replicate the ...

Security measures for interacting with REST API by both frontend application and secondary backend service

I currently have a REST API backend service A that is being utilized by two other services: B service, which is a web app running in a browser (on a separate node server) C service, which is also a backend service (running on a separate server) Initiall ...

Steps to convert the value from False to True with just a simple press of a

I'm currently learning React.js and I wanted to create this specific application. My goal is to figure out how to toggle between False and True using action buttons. Whether you can provide an explanation or show me an example, it would be greatly app ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

What is the best method for retrieving the selected itemsPerPage in Vuetify's data-table in version 2.0

Recently, I've been struggling to retrieve the selected items-per-page on a Vuetify data-table due to some recent changes. I came across this helpful example: How to set initial 'rows per page' value in Vuetify DataTable component? Here is th ...

Trouble displaying REACT.jsx in browser

I'm currently learning React and struggling to get it running smoothly. HTML function Person(){ return ( <div class="person"> <h1>Max</h1> <p>Your Age: 28</p> </div> ); } ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

How can I customize the error message for chai expect in my mocha unit test?

I'm working on a mocha test that uses chai's expect function: it("should parse sails out of cache file", async () => { const sailExtractor = new Extractor(); const result = await sailExtractor.extract("test.xml"); try { e ...

Executing two distinct SQL queries within one nodejs function

I'm facing an issue with updating two tables in my database - the stockmaster table and the prodstock table. I've been trying to run a query using a function to update both tables simultaneously, but unfortunately, it's not working as expect ...

Is it possible to change all text to lowercase except for URLs using .tolowercase()?

Currently, I am facing a challenge with my Greasemonkey script. The use of .tolowercase() is causing all uppercase letters to be converted to lowercase, which is disrupting URLs. I have explored alternatives like .startswith() and .endswith(), considering ...

none of the statements within the JavaScript function are being executed

Here is the code for a function called EVOLVE1: function EVOLVE1() { if(ATP >= evolveCost) { display('Your cell now has the ability to divide.'); display('Each new cell provides more ATP per respiration.'); ATP = ATP ...

Determine the quantity of classes based on the part name

I have the code snippet provided below: <ul id="towns"> <li class="clearfix odd 516_499_132_0_0 town132">...</li> </ul> I am looking to extract the specific class "town132" as a parameter, but the number - such as 132 in this ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...