using javascript to get array element when hovering

I am currently exploring ways to retrieve and display the value of a div tag created with a 2D array using JavaScript. I have considered using onclick or onmouseover, but so far, neither approach has worked as expected. I am looking for a solution that avoids creating multiple functions to simply display the cell the cursor is over.

<style type="text/css">
  .float {float: left;}
  .clear {clear:both;}
  div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
    <div id="grid"></div>
    <div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;

for (var i = 0; i < axisY; i++) {
  for (var j = 0; j < axisZ; j++) {
    document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(cellId)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
  }
  document.getElementById('grid').innerHTML += "<br class='clear' />";
}

function displayMe(cellId) {
  // ???
}

function displayNone() {
  document.getElementById('bucket').innerHTML = "";
}
</script>

Thanks!

Answer №1

To retrieve the cell id, simply pass this.id as a parameter to the designated function.

Attempt the following:

<script type="text/javascript>
var row = 7;
var column = 7;

for (var i = 0; i < row; i++) {
  for (var j = 0; j < column; j++) {
    document.getElementById('grid').innerHTML += "<div onmouseout='hideCell()' onmouseover='showCell(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
  }
  document.getElementById('grid').innerHTML += "<br class='clear' />";
}

function showCell(cellId) {
  console.log(cellId);
}

function hideCell() {
  document.getElementById('bucket').innerHTML = "";
}
</script>

Answer №2

At this moment, every cell element is set up to trigger the function displayMe when the mouseover event occurs. However, when this function is called, the variable cellId is not defined, resulting in an error message in the browser console ("Uncaught ReferenceError: cellId is not defined").

To resolve this issue, you should pass the dynamically defined id property of the cell element, which can be accessed using this.id. By changing the onmouseover attribute of the div element to onmouseover='displayMe(this.id)', you can ensure that the correct value is passed to the displayMe function.

Here is the adjusted code snippet that includes these changes:

<style type="text/css">
  .float {float: left;}
  .clear {clear:both;}
  div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
    <div id="grid"></div>
    <div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;

for (var i = 0; i < axisY; i++) {
  for (var j = 0; j < axisZ; j++) {
    document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
  }
  document.getElementById('grid').innerHTML += "<br class='clear' />";
}

function displayMe(cellId) {
  document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}

function displayNone() {
  document.getElementById('bucket').innerHTML = "";
}
</script>

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

Adding JSON data to an array in Angular JS using the push method

I am encountering difficulties with adding data to an existing array. Currently, I have set up a table to display the data, but I want to also include the data in the table when a user enters an 8-digit barcode. Factory angular.module('app.pickU ...

Modifying the appearance of a CSS element with jQuery: Step-by-step guide

The code I have is as follows: $('.signup-form-wrapper').css("style", "display: block"); $('.login-form-wrapper').css("style", "display: none"); I'm not sure why it's not working. The current appearance of ...

Exploring the proper method for closing connections in Node JS and the pg module

I'm experiencing frustration with the node pg module as I keep encountering a 'too many clients already' error. For instance, in my app.js file, I handle various routes where I query data from postgres. Here's a snippet of how app.js i ...

Tips for modifying AJAX behavior or restricting requests in Wicket

I am looking to prevent updates based on a specific JavaScript condition using AjaxSelfUpdatingTimerBehavior. WebMarkupContainer messagesWmc = new WebMarkupContainer( "messagesWmc" ) ; messagesWmc.setOutputMarkupId( true ) ; messagesWmc.add( ...

How to Share an Array Across Two Java Classes

Adhering to good OOP practices, I am attempting to split some of my methods into two separate classes (not the main class). Both classes rely on a specific 2D array in order to ensure the program functions correctly: private char [][] board = new char[7] ...

Placing jQuery in the lower part of my HTML templates lacks adaptability

Lately, I've been optimizing my templates by placing the jQuery code link at the end of the template files to ensure fast page load speeds. Along with that, I have specific javascript modules reserved for certain pages that are included within the con ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

Jasmine examination fails to progress to the subsequent segment of the promise

I want to test a specific function: function initializeView() { var deferred = $q.defer(); if(this.momentArray) { core.listMoments(constants.BEST_MOMENT_PREFIX, '').then(function(moments) { //Ommit ...

There is a lack of 'Access-Control-Allow-Origin' header - Issue encountered while making Food2Fork API request using AJAX

Our team has just embarked on our first project, and I've encountered a roadblock while conducting API testing. Specifically, I am struggling to generate a successful access control header. Is there anyone who can provide assistance in troubleshooting ...

Tips for retrieving email addresses from a intricate array

Is there a way to filter only emails and store them in a basic array? Appreciate your help! ...

Combining two objects in AngularJS to create a new merged object

Is there a way to merge object1 and object2 into object3, updating values corresponding to matching keys while ignoring unmatching keys? var object1 = { "pii" : "val1", "loc" : "val2" } var object2 = { "rrb" : "val3", "voc" : "val4" } var obje ...

Creating a Vibrant Progress Bar with Multiple Colors: A Step-by-Step Guide

I'm still getting the hang of things, so I apologize if my question isn't perfectly clear. What I'm trying to do is create a dynamic progress bar with multiple colors that animates upon loading the page. I've seen some examples similar ...

Locate the present position of the slider element

I am currently in the process of creating a website that features pages displayed in a slider format. Each page has its own unique ID, but all share a common class called 'section'. However, I am encountering difficulty in identifying the ID of t ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Implementing a clickable image using an anchor tag in JavaScript

I need to enhance my image tag in JQuery by adding an anchor tag alongside it. How can I accomplish this using JavaScript? Here is what I attempted: var imgg = document.createElement("img"); imgg.className='myclass'; $( ".myclass" ).add( "<a ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...

PHP: what is the best way to efficiently replace these specific strings?

Currently, I am utilizing array_intersect() in my Wordpress menu-items to eliminate all classes, with the exception of a specified list. Following this, I am using str_replace to rename the classes. While this method works, it does seem somewhat messy. Is ...

Avoid displaying "undefined" on HTML page when Firebase database value is empty

I am trying my best to explain my issue, although I struggle with scripts. Please bear with me and help me improve. ˆˆ Below is the script I am working on. The goal is to display all records with a date set for 'today or in the future'. Progr ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

Form validation on the client side: A way to halt form submission

I have a form with several textboxes. The unobtrusive jquery validation is functioning properly and correctly turns the boxes red when invalid values are entered. However, I've noticed that when I click to submit the form, it gets posted back to the s ...