FSS FSS - 3 months ago 14
HTML Question

converting area element to div

I am a beginner in Javascript/jQuery. Thank you for reading!

EDIT:
Here is a jsfiddle with all of the code (annotated) https://jsfiddle.net/sfs1926/n1sopf79/
It does not work, but here is a working example video of what my code does so far: https://www.youtube.com/watch?v=N67Bx9jgPFo

The context is: I am trying to model layers of electronics (represented as rectangles) on a graph. There are 10,000 overlapping rectangles (each representing the position of a piece of electronics). I write these area elements in line by line from a text file that contains the coordinates of each rectangle and its title. I associate each area element with its title using an overlay id. My goal: When I mouse over a pixel on the graph, I want to display ALL rectangles associated with that pixel and their overlay id's (to the side, off the graph). So far I am able to do all of this besides displaying the rectangles.

Right now I have a HTML map 'demo' containing many area elements (all rectangles). I want to use jQuery to push each of those area elements into the array elementPositions. This I do successfully below, but with one exception: I want to create the identifier 'element' to be that area element written as a div with css. This is because I want to show and hide rectangles belonging to elementPositions using the .show() method. That is why I am converting the area elements to be divs.

Can someone help me with the syntax for how to do this conversion? I think the reason why no rectangle will 'show' is because I have not set the display or the background attribute of the div, but I'm not sure how to do this.

if( $('#demo').length >0 ) {

var elementPositions = [];

$('#demo area').each(function() {
var offset = this.coords;
var coordarray = offset.split(",");
var left = coordarray[0];
var top = coordarray[1];
var right = coordarray[2];
var bottom = coordarray[3];
var id = this.id;
var wid = right - left;
var hei = bottom - top;
var hoveredElements = [];

elementPositions.push({
element: $('<div class="area"></div>')
.css({position: 'absolute', left: left, top: top}).
width(wid).height(hei), // attempt so far!
top: top,
bottom: bottom,
left: left,
right: right,
id: id,
});


Then I hope to do something like:

$("body").mousemove(function(e) {
elementPositions.forEach( function(item) {
item.element.show();
});
}

Answer

you need to append your div before show it, append to body for example :

var elementDiv = $('<div class="area"></div>')
                        .css({position: 'absolute', left: left, top: top}).
                        width(wid).height(hei);
$("body").append(elementDiv );
elementDiv.hide();

elementPositions.push({ 
                    element: elementDiv ,
                    top: top, 
                    bottom: bottom, 
                    left: left, 
                    right: right, 
                    id: id, 
                });