rob.m rob.m - 1 year ago 73
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:

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

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


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

But I believe I should use
since it is a
svg path

Answer Source

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;
} {
    border: 5px solid red;
<script src=""></script>
<h4>Note: I used a different element for this demo. Just change it to the needed elements and also update the script</h4>
    <p class="myClass"></p>
    <p class="myClass active"></p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download