rob.m rob.m - 29 days ago 6
Javascript Question

Stop hover and click on element with not specific class attribute

I want to disable the hover (and click) on elements which do not have a specific class name attribute:

<svg>
<path class="myClass"></path>
<path class="myClass active"></path>
</svg>


Basically if path has not attribute className "active" don't hover or click

Tried:

if (!$("path").hasClass("active")) {
$(this).unbind('mouseenter mouseleave');
};


But I believe I should use
.attr("class"..)
since it is a
svg path

Answer

This demo uses the .attr() function. with this you will have to loop through each desired element and loop its class list (if exist) and see if it contains the .active class if not then unbind the events of that element.

$('p').on('mouseenter', function() {
    $(this).css('background', 'blue');
})

$('p').on('mouseleave', function() {
    $(this).css('background', 'black');
})


$('p').each(function(indx, elem) {
    var activeNotFound = 1;
    var classes = [];
    if ($(elem).attr('class') !== undefined) { // check if elem has attribute class
    	classes = $(elem).attr('class').split(" "); // split into array the attribute class
        $.each(classes, function(ndx, classname) { // loop each class to check if active exist
            if (classname === 'active') {
                activeNotFound = 0;
            }
          // removed the else part.
        });
    }
    
    if (activeNotFound) { // if no active class found unbind events
        $(elem).unbind('mouseenter mouseleave')
    }
})
div p {
    width: 100px;
    height: 100px;
    background: #000;
    border: 5px solid #000;
}

p.active {
    border: 5px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Note: I used a different element for this demo. Just change it to the needed elements and also update the script</h4>
<div>
    <p class="myClass"></p>
    <p class="myClass active"></p>
    <p></p>
</div>