javascripthtmljqueryarraysjquery-hover

How to apply mouseenter/mouseleave on multiple paired divs


I'm trying to hover on div and affect another. Took a shot at it but my code is a bit clunky. Is there a shorter and better way to do this? This is the short version of the code, I need to apply this 70 more times.

// hover and highlight corresponding box
$("#txt01").on({
    mouseenter: function () {
        $('#txt01').css('border-color', '#cc0000');
        $('#img01').css('border-color', '#cc0000');
    },
    mouseleave: function () {
        $('#txt01').css('border-color', '#0099ff');
        $('#img01').css('border-color', 'transparent');
    }
});
$("#txt02").on({
    mouseenter: function () {
        $('#txt02').css('border-color', '#cc0000');
        $('#img02').css('border-color', '#cc0000');
    },
    mouseleave: function () {
        $('#txt02').css('border-color', '#0099ff');
        $('#img02').css('border-color', 'transparent');
    }
});
$("#txt03").on({
    mouseenter: function () {
        $('#txt03').css('border-color', '#cc0000');
        $('#img03').css('border-color', '#cc0000');
    },
    mouseleave: function () {
        $('#txt03').css('border-color', '#0099ff');
        $('#img03').css('border-color', 'transparent');
    }
});


Solution

  • Assuming you aren't using classes, which in this case I highly recommend, you can use ^ next to the ID to get any id starting with txt.

    $(document).ready(function() {
      $("[id^=txt]").on("mouseover", function(e) {
        var id = $(e.target).prop("id").replace("txt", "");
        $('#txt' + id).css('border-color', '#cc0000');
        $('#img' + id).css('border-color', '#cc0000');
      });
    
      $("[id^=txt]").on("mouseout", function(e) {
        var id = $(e.target).prop("id").replace("txt", "");
        $('#txt' + id).css('border-color', '#0099ff');
        $('#img' + id).css('border-color', 'transparent');
      });
    });
    div {
      border: 1px solid #000;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="txt01">10</div>
    <div id="img01">01</div>