There are many duplicate scripts, for example:

$('.yo_block').on('mouseenter', function() { var offset = $('.yo_block').offset(); $('#vk_follow_block').hide(); $('#fb_follow_block').hide(); $('#google_follow_block').hide(); $('#youtube_follow_block').show() .css({ 'top': offset.top - 120 + 'px', 'left': offset.left + 0 + 'px' }) .on('mouseleave', function() { $(this).hide(); }); $(".yo_block").mouseleave(function(e) { var $this = $(this); var bottom = $this.offset().top + $this.outerHeight(); if (e.pageY >= bottom) { $('#youtube_follow_block').hide(); } }); }); $('.gog_block').on('mouseenter', function() { var offset = $('.gog_block').offset(); $('#vk_follow_block').hide(); $('#fb_follow_block').hide(); $('#youtube_follow_block').hide(); $('#google_follow_block').show() .css({ 'top': offset.top - 120 + 'px', 'left': offset.left + 0 + 'px' }) .on('mouseleave', function() { $(this).hide(); }); $(".gog_block").mouseleave(function(e) { var $this = $(this); var bottom = $this.offset().top + $this.outerHeight(); if (e.pageY >= bottom) { $('#google_follow_block').hide(); } }); }); 

Is it possible to reduce it?

  • $ ('# fb_follow_block') and so on, define the variables var blockN .... - Jean-Claude
  • Can! You wanted to see this answer? And on the topic, the code is the same, put into function. You have only the internal block yo_block and gog_block changing there. - Vasily Barbashev

1 answer 1

Can and should be.

We look closely at the two pieces and understand that they differ only in the names of the two classes. Put them in the function parameters and do something like this.

 function do($main_block, $social_block) { $($main_block).on('mouseenter', function(){ var offset = $($main_block).offset(); // эти скрытия лучше сделать через цикл $('#vk_follow_block').hide(); $('#fb_follow_block').hide(); $('#google_follow_block').hide(); $('#youtube_follow_block').hide(); $($social_block).show() .css({'top': offset.top - 120 +'px', 'left': offset.left + 0 + 'px'}) .on('mouseleave', function(){ $(this).hide(); }); $($main_block).mouseleave(function(e) { var $this = $(this); var bottom = $this.offset().top + $this.outerHeight(); if(e.pageY >= bottom){ $($social_block).hide(); } }); }); } 

and call

 do('.yo_block', '#youtube_follow_block'); do('.gog_block', '#google_follow_block'); 
  • Super! Thank! - Alexander Reizan
  • And the blocks that hide ()? How to deal with them? - Alexander Reizan
  • As you can see, I first added the hiding of all the blocks, and then the necessary one is displayed. Do you want me to write a loop to hide all the blocks? - KoVadim
  • The fact is that I can write it myself, but most likely it will not work, I want to compare my code with the code of a specialist. - Alexander Reizan
  • one
    I am not a javascript specialist. I strongly recommend that you write your own. - KoVadim