Home > Software engineering >  How to add class to only selected div based on hover
How to add class to only selected div based on hover

Time:12-31

I am trying to add class to mainmenu div, but for some reason it add class to both the div, the div has same class, i only wanted to add class to selected div.

<div >
    <div id="col1">
        <div >hidden text</div>
    </div>
    <div id="col2" >
        <div >
            <a >toggleClass</a>
            <a >toggleClass</a>
            <a >toggleClass</a>
        </div>
        <div >
            <a >toggleClass</a>
            <a >toggleClass</a>
            <a >toggleClass</a>
        </div>
    </div>
    <div id="col3" >
        <div >
            <div >
                <a >toggleClass</a>
                <a >toggleClass</a>
                <a >toggleClass</a>
            </div>
        </div>
        <div >
            <div >
                <a >toggleClass</a>
                <a >toggleClass</a>
                <a >toggleClass</a>
            </div>
        </div>
    </div>
</div>

This is my JQUERY code.

(function($) {
  $(document).ready(function() {
    $('.menubox .toggleClass').hover(function() {
      // fade in the div in this object.
      $(this).closest('.main-coloumn').find('.class .mainmenu').toggleClass('class_name');
    });
  });
}(jQuery));

CodePudding user response:

I think you might want something like:

    (function($) {
        $( document ).ready( function() {
            $('.menubox .toggleClass').hover(function () {
                var mine. = $(this).closest('.mainmenu');
                $(this).closest('.main-coloumn').find('.mainmenu').not( mine ).removeClass('class_name');
                mine.addClass('class_name');
            });
        });
    }(jQuery));

CodePudding user response:

Working Demo: https://dojo.telerik.com/IJoBeCeT/2

(function($) {
  $(document).ready(function() {
    $('.menubox .toggleClass').hover(function() {
      // fade in the div in this object.
      $(this).parents('.mainmenu').toggleClass('class_name');
    });
  });
}(jQuery));
.class_name {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    <div id="col1">
        <div >hidden text</div>
    </div>
    <div id="col2" >
        <div >
            <a >toggleClass</a>
            <a >toggleClass</a>
            <a >toggleClass</a>
        </div>
        <div >
            <a >toggleClass</a>
            <a >toggleClass</a>
            <a >toggleClass</a>
        </div>
    </div>
    <div id="col3" >
        <div >
            <div >
                <a >toggleClass</a>
                <a >toggleClass</a>
                <a >toggleClass</a>
            </div>
        </div>
        <div >
            <div >
                <a >toggleClass</a>
                <a >toggleClass</a>
                <a >toggleClass</a>
            </div>
        </div>
    </div>
</div>

  • Related