Search code examples
javascriptjquerycsscanvaskonvajs

Adding and removing classes on mouse enter and leave on canvas shape


I'm trying to add a class to a element when mouse hovers over it and then remove it when mouse leaves. It works currently only with giving it direct style in js.

As shown below I tried various ways to do this, all had some problems. Only the direct style change worked. On mouse leave I do the same but remove the class. The mouse over and leave checks canvas element.

poly.on('mouseover', function () {
                this.opacity(1);
                layer.draw();
                $('.' + this.name()).css({ backgroundColor: "#ffcc00" });
                //$('.' + this.name()).classList.add("textboxhighlight"); 
                //$('.' + this.name()).className += " textboxhighlight";  
                //$('.' + this.name()).addClass("textboxhighlight"); 
                //$('.' + this.name()).setAttribute("class", "textboxhighlight"); 
            });

I'm not sure what the problem is as I tired various methods in adding class all of them with different problems. Using just this.addClass wont work as it needs to start with $('.' + this.name()) or nothing works in the code not even forcing the style part. $('.' + this.name()) refers to a class name in element with the same name as poly.

In css:

.textboxhighlight {
    background-color: #ffcc00;
}

Thanks for any help.


Solution

  • May be you have to use in your css class background-color: #red !important. See working example here