Home > Blockchain >  Jquery incrementation function with ID and Hover
Jquery incrementation function with ID and Hover

Time:11-13

How i can write this function below without to repeat each time the same code. Thanks for your help.

        $("#zone-1").hover(function(){
            $("#projects-1").addClass('visible');
        }, function(){
            $("#projects-1").removeClass('visible');
        });

        $("#zone-2").hover(function(){
            $("#projects-2").addClass('visible');
        }, function(){
            $("#projects-2").removeClass('visible');
        });

        $("#zone-3").hover(function(){
            $("#projects-3").addClass('visible');
        }, function(){
            $("#projects-3").removeClass('visible');
        });                     

        $("#zone-4").hover(function(){
            $("#projects-4").addClass('visible');
        }, function(){
            $("#projects-4").removeClass('visible');
        });

CodePudding user response:

As suggested by @connexo you could use classes instead of ids.

This code might need some adjustments because you did not provide your HTML.

$(".zone").hover(function(){
    $(this).next(".projects").addClass("visible");
}, function() {
    $(this).next(".projects").removeClass("visible");
}

CodePudding user response:

Use https://api.jquery.com/attribute-starts-with-selector/ to get element with starting attribute value like yours : "zone-". Then get id of the current hovered element with $(this).attr('id');

Finally, split the id with the separator "-" and then get second element of this array "[1]". https://www.w3schools.com/jsref/jsref_split.asp

Its better to use toggleClass() : https://api.jquery.com/toggleclass/ because your changing class name is same.

$("div[id^='zone-']").hover(function(){
   // current id number
  let getDivID = $(this).attr('id').split('-')[1];
  $("#projects-"   getDivID).toggleClass('visible');
  
  // debug infos
  console.clear();
  console.log(getDivID);
});
.projects { display:none }
.visible { display:block }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="zone-1">zone-1</div>
<div id="zone-2">zone-2</div>
<br><br>
<div id="projects-1" class="projects">projects-1</div>
<div id="projects-2" class="projects">projects-2</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related