Arthur
Arthur

Reputation: 5148

Mouseenter/Mouseleave on SVG use and jQuery

I'm building my menu's website with SVG picture and I have a probleme with jQuery and the mouseleave event..

This is my HTML / CSS :

<div style="display:none;">
    <svg id ="home-icon" viewBox="0 0 64 64">
        <path  d="M57.0 <!-- .. SVG source Here ... --> 98z"/>
    </svg>
</div>
<ul id="top-menu">
    <li class="menu-icon">
        <svg><use xlink:href="#home-icon" /></svg>
    </li>
</ul>
.menu-icon svg{
    fill: #AB1;
    width:64px;height:64px; 
}
.menu-icon.active svg{
    background: #AB1;
    stroke: #e8e8e8;stroke-width: 2px;
}

And the jQuery :

$('.menu-icon').mouseenter(function(){
    $(this).addClass('active');
}).mouseleave(function(){
    $(this).removeClass('active');
});

-> Code here <-

But when the mouse is on the svg balise, I have a trigger 'mouseleave' on my li.menu-icon.. I ready don't understand why ?!

Thank you all for reading and help !

Upvotes: 4

Views: 5629

Answers (3)

Marcatectura
Marcatectura

Reputation: 1695

I'm late to the party here, but recently encountered this problem and wasn't interested in over-complicating my jQuery to prevent mouseleave when the pointer was over an SVG icon. I found that the CSS property

pointer-events: none; 

can solve this issue if it's applied to the SVG - in fact, the property is part of the SVG recommendation and is specifically intended for similar situations: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Upvotes: 7

Rob Sedgwick
Rob Sedgwick

Reputation: 5226

When we use <svg><use .. we do not actually copy the svg into our container node. So we are actually triggering mouse out

See http://jsfiddle.net/8RCyD/5/ - Updated link from @Erik with up to date version of jquery, solving the cross browser discrepancies discussed, thanks

We could

$(".menu-icon").append("#menu-icon"); /* the svg we want */

.. first and then ..

$('.menu-icon').mouseenter(function(){
    $(this).addClass('active');
}).mouseleave(function(){
    $(this).removeClass('active');
});

Upvotes: 3

Felix
Felix

Reputation: 38102

Instead of jQuery, you can just use pure CSS:

.menu-icon:hover svg {
    background: #AB1;
    stroke: #e8e8e8;
    stroke-width: 2px;
}

Updated Fiddle

Upvotes: 0

Related Questions