Retrieve the identification of a randomly selected div element using an array

I am attempting to implement a right-click function using only JavaScript. My initial plan was to utilize a mouseover function, as shown below:

mysteryDiv.onmouseover=function(){
    if (rightMBclicked === true)
    {
    console.log(mysteryDiv.id);
    }
}

The dilemma I am facing is figuring out how to access 'mysteryDiv'. Below is the function responsible for generating the blocks that I need to interact with, along with some key variables:

var blocknum = 0;
var blockmax = 2500;
var blocks = [];

function createBlocks()
    {
    if (blocknum < blockmax)
    {
    blocknum += 1;
    var block = document.createElement("div");
    block.className = "block"; 
    block.id = "block" + blocknum;
    blocks.push(blocknum);
    block.style.width = block_width + "px";
    block.style.height = block_height + "px";
    block.style.cssFloat = "left";
    //block.style.backgroundColor = "#228B22";
    block.style.backgroundImage="url('textures/grass.jpg')";
    document.getElementById("container").appendChild(block,container.firstChild);
    createBlocks();
    }
    else
    {
    if (blocknum === blockmax)
    {
    createPlayer();
    paused = false;
    }
    }
    }

EDIT:

My objective is to retrieve the ID of the block (mysteryDiv) currently under my mouse cursor.

Answer №1

If you need to manage events for dynamically generated blocks, consider the following approach. Make sure to set rightMBclicked to true for test cases.

//after this line
block.style.backgroundImage="url('textures/grass.jpg')"; 

//here
block.onmouseover = function(e){

    if (rightMBclicked === true)
    {
        console.log(e);
        console.log(this.id);
    }
};

//before this line
document.getElementById("container").appendChild(block, container.firstChild);

Answer №2

Upon initial observation, you may find it necessary to assign the same event handler to all of your div elements.

One possible approach is as follows:

customHandler = function(e)
{
        console.log(e)

}

allDivs = document.getElementsByTagName("div")

for (i in allDivs)
    allDivs[i].onmouseover = customHandler

However, be cautious of event bubbling. It might be beneficial to provide more details on your HTML structure for better assistance.

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

Encountering a problem with the getJSON() function within the app.js file connected to a solidity

Currently, I am working on developing a simple dapp in Truffle. However, I encountered an error when using $.getJSON() function in my app.js file. Below is a snippet of my app.js: App ={ web3Provider: null, contracts: {}, init: function (){ return A ...

Issues with AngularJS edit functionality for records not functioning as expected

I have implemented a feature on my page where users can add objects to an array. These objects are then displayed on the page along with links for editing each item in the array. Each added item is assigned a primary key, allowing users to edit it later e ...

Looking to expand your understanding of arrays?

I came across this code while trying to learn about Arrays. Although the code is functioning properly, I have a few questions. What does (10) mean in line var ascendingArray = new Array(10);? Also, what exactly is happening with the code employees = empl ...

Showcasing a JSON file in the interface using $http in AngularJS

I am a beginner in angularjs (and programming). I am attempting to showcase a json file on my view (home.html) using $http and ngRepeat, but unfortunately, it is not working as expected. Upon inspecting the angular responses, I noticed that there are numer ...

Save the contents of a file within an HTML table using jQuery

I needed to insert multiple files into the database by uploading and adding each file's content to a table. Once all files were added to the table, I included the table's values along with the file content in form data which was then passed to aj ...

Using URLs to customize the colors of line graphs in C3.js

I'm currently facing an issue with customizing the colors of my line graph created from JSON data retrieved from a URL. Below is the code snippet I'm using to generate the chart: var chart = c3.generate({ bindto: '#chart', data: { ...

Observable not defined in facade pattern with RxJS

(After taking Gunnar's advice, I'm updating my question) @Gunnar.B Tool for integrating with API @Injectable({ providedIn: 'root' }) export class ConsolidatedAPI { constructor(private http: HttpClient) { } getInvestments(search?: ...

Transforming HTML into a Console Experience (Angular 16)

I'm experimenting with creating a console/CLI style experience using HTML. The goal is to have the input fixed at the bottom of the window, while commands and output rise up from the bottom and eventually disappear off the top of the screen, enabling ...

One method of dirty checking using a shared service among controllers is effective, while the other method is not successful

As I was trying to solve the problem of sharing data between two separate controllers, I encountered a curious issue. Usually, I rely on services for this task and started creating a jsfiddle example, but unfortunately, I couldn't get it to function ...

Custom components receive specific values through Styled Components

Hey there! I'm currently working on customizing the color of a button based on its type within a modal. The button can be categorized as either "Success" or "Danger": import React from "react"; import styled from "styled-components" ...

Rearrange the order of elements within an array and move elements around within it

I am looking to select an element from an array, relocate it to a different index, and then shift the elements in-between by 1 position. Consider this as drag-and-drop functionality, where if the starting index (from) is less than the destination index ( ...

Nodemailer attachments are missing contents

I'm having trouble attaching files to emails using NodeMailer. When I check the sent email, the attachments appear as empty files with 0 bytes. Even when I download them, they are still empty text files. Can someone please help me identify what I migh ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

Adding up the elements of an integer array in C to produce a final result

I've encountered an issue with a function I've created. It calls another function, checks a condition for truth, and then increments an integer accordingly. Everything works well, but once the results become very large, I face a problem. The numb ...

Press the "Enter" key to automatically submit the form and validate the input

How can I make my form submit when the "enter" key is pressed? Currently, I have set the button type as "submit" so that the form is submitted when enter is pressed. However, I also want to call a function with validation and confirmation. Right now, it&ap ...

Scroll through all pages by pulling down on the mouse wheel with Selenium

Attempted to emulate the mouse wheel for loading all elements. Despite extensive Google research and multiple attempts, I was unsuccessful. from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # Configuration informa ...

Converting matrix into a new array by assigning only certain columns

I have a numeric matrix with dimensions 17 (rows) x 6 (columns). Here is what it looks like: https://i.sstatic.net/UakYh.png My goal is to convert this matrix into an array of size 2 (rows) x 3 (columns) x (17 dimensions), where each row in the original ...

Determining the Nearest Date in an Array Using JavaScript

In my array, I store information about each day as an object. For example: {day_year: "2012", day_month: "08", day_number: "03", day_name: "mon"} To enhance the day objects, I have included a timestamp attribute using the following function: function co ...

JavaScript code: "Retrieve the div element and append metadata to the HTML file

Currently, I am utilizing the subsequent technique to save a target tag on my webpage as an HTML file. function retrieveHtml(filename, elId, format) { var htmlEl = document.getElementById(elId).innerHTML; if (navigator.msSaveBlob) { // IE 10+ ...

Enhancing an existing node by adding a new node with jQuery functionalities at the same time

Is it possible to append a node to a parent node while also manipulating the node being added? I initially believed this could be done in one step: //I though this was possible: $('#master').after('<div id="test" style="border:solid 1px ...