0

I am a beginner in Javascript/jQuery/CSS/HTML. Thanks for reading!

My code uses an XML request to read multiple text files line by line into Javascript. Each line holds the coordinates of a rectangle and the rectangle's associated overlay text. Shown in the code snippet below, I create an area element (a rectangle) for each line of the text file. I then append each area element to the map 'demo'. Then I converted all of these area elements into div CSS elements so I can show and hide the rectangles using jQuery .show() method. The trouble with this is that there are so many rectangles that there is a noticeable lag when I use .show().

So I have been trying to implement the CSS hover selector to display the rectangles more instantaneously and have been stuck on the syntax. All my rectangle CSS divs (seen in the code below) are of the class "area". I have tried things like this in the HTML head:

<style>
.area:hover {
  background: blue;
}
</style>

But no results. I'm thinking I have to somehow execute the 'hover' action in jQuery but don't know how to do this.

Here is a jsfiddle that describes what I want to achieve: https://jsfiddle.net/d1amzfLx/4/

Here is a code snippet, which begins right after I begin the for loop over the multiple text files and start reading in the rectangles as area elements, and ends after each rectangle corresponding to the pixel I mouse over (and its overlay id) is shown.

    // get text contents by looping over i text files
        j=20000*i + 50000;
        var coords = xhr[i].responseText.split("\n");
        coords = coords.filter(Boolean) //prevents extra rect with 0 coords
        coords.forEach(function(coord) { 
                var area = document.createElement("area");
                area.id = "r"+j;
                area.shape = "rect";
                area.coords = coord.substring(10,coord.length).trim().replace(/ +/g,",");    // replaces spaces in txt file with commas
                area.href = "#";
                area.alt = "r"+j;

                // create overlay with first term in string
                var div = document.createElement("div");
                div.className = "cont";
                div.id ="overlayr"+j;
                div.innerHTML = coord.substring(0,10);
                div.style.display = "none";
                //increase j
                j++;

                document.getElementById("demo").appendChild(area);
                document.getElementById("demo").appendChild(div);
                //all rectangles and their overlay texts are appended to the map 'demo'
            }); 


        //display rectangles and overlay ids by mousing over

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

            var hoveredElements = [];
            var elementPositions = [];

            $('#demo area').each(function() {
            var offset = this.coords;
            var coordarray = offset.split(",");
            var l = coordarray[0];
            var t = coordarray[1];
            var r = coordarray[2];
            var b = coordarray[3];
            var ident = this.id;
            var w = r - l;
            var h = b - t;  
            var elementDiv = $('<div class="area"></div>')
                .css({position: 'absolute', left: l + 'px', top: t + 'px', border: 'solid', borderColor: 'green' }). 
                width(w).height(h);

            $("body").append(elementDiv);
            elementDiv.hide();      

            //console.log("Top =" + top + ",Left =" + left + ",Bottom =" + bottom + ",Right =" + right); 

            elementPositions.push({ 
                element: elementDiv,
                top: t, 
                bottom: b, 
                left: l, 
                right: r, 
                id: ident, 
            });

                    }); //end of demo area

            //console.log("elementPositions.length=" + elementPositions.length);
            $("body").mousemove(function(e) {
            //console.log("clearing hovered elements");
            hoveredElements.forEach( function(item) {
                item.overlay.hide();
                item.element.hide();
            });

            hoveredElements = [];

            var xPosition = e.pageX;
            var yPosition = e.pageY;
            //console.log(xPosition,yPosition);

            for (var ie = 0; ie < elementPositions.length; ie++) { 
                var id = elementPositions[ie].id;
                    if (xPosition >= elementPositions[ie].left && 
                  xPosition <= elementPositions[ie].right &&
                  yPosition >= elementPositions[ie].top &&
                  yPosition <= elementPositions[ie].bottom) {
                    // The mouse is within the element's boundaries
                    //console.log("Element" + ie + "hit");
                        hoveredElements.push({ 
                         overlay: $('#overlay' + id),
                         element: elementPositions[ie].element,
                    });
                     } 
            } //end of for loop over all elements

            hoveredElements.forEach( function(item) {
                item.overlay.show();
                //item.element.show(); this command shows the CSS div rectangles, but they take too long to load!
            });//end of for loop over all hovered elements

                        }); //end of mousemove function

        }; //end of if demo
7
  • Would you be able to post an example on jsfiddle.net or similar? I'm not understanding exactly what you are doing, but a CSS hover should be easy to sort out which will be better for performance than invoking jQuery Commented Aug 17, 2016 at 18:25
  • I am not able to post an example on jsfiddle quickly but here is a youtube video demonstrating the code animation currently: youtube.com/watch?v=s-E_VFbRruc Commented Aug 17, 2016 at 18:27
  • You append <div> you created to <map> element which is not allowed. Commented Aug 17, 2016 at 18:28
  • So @FSS this happends onmouse move or mouseclick? Commented Aug 17, 2016 at 18:29
  • It happens on mousemove Commented Aug 17, 2016 at 18:31

1 Answer 1

1

This will change all the divs with the class .area to background-color:blue;

$(document).on("mouseenter", ".area", function() {
    $( '.area' ).css('background-color','blue');
});

This is when your mouse leaves. By default color i mean the background color that divs had before changing to blue

$(document).on("mouseleave", ".area", function() {
    $( '.area' ).css('background-color','defaultColor');

});

Also for a better performance you should replace the document with an .area parent id or class

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks for the comment! What do you mean by '.whateverClass'? And would you insert those lines right after the "hoveredElements.forEach( function(item) {" line?
the '.whateverClass' is the element class that will trigger this function when you hover. So for example '.menu' means that when you hover on menu this function will be triggered and the '.area' will fadeIn
I'm still a little unsure what you mean by "the '.area' will fadeIn". My rectangle css divs are all of the class '.area', so that would replace '.menu' in your example..
So you want to create this : when you hover over your divs with class 'area' the background of that div change to blue ? or all divs should change background to blue ?
Yes, when I hover over the divs with class 'area' I want the background of only those divs in the hoveredElements array to change to blue.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.