How to clean up this jQuery snippet correctly

I'm using this jQuery snippet to change the background position of a image, when the links are hovered. But I have to add alot more selectors to it, and it's going to take up alot of lines this way, but I cannot seem to find a way to minify it? Can it be done? Or maby there is a more correct way to do this background changing?

<script type ="text/javascript">
jQuery(function(){
jQuery(".1-panel").hover(function(){
    jQuery(".panel-image").css('background-position','0px -135px');
});
jQuery(".2-panel").hover(function(){
    jQuery(".panel-image").css('background-position','0px 0px');
});
jQuery(".3-panel").hover(function(){
    jQuery(".panel-image").css('background-position','0px -265px');
});
jQuery(".4-panel").hover(function(){
    jQuery(".panel-image").css('background-position','0px -560px');
});
jQuery(".5-panel").hover(function(){
    jQuery(".panel-image").css('background-position','0px -410px');
});
});
</script>

Answers


I'll add a common class like panel to all the 5 elements 1-panel, .... 5-panel, also add an additional data-* attribute like data-imagebp like

<div class="1-panel panel" data-imagebp="0px -135px">...</div>
<div class="2-panel panel" data-imagebp="0px 0px">...</div>
...
<div class="5-panel panel" data-imagebp="0px -410px">...</div>

then

jQuery(function ($) {
    var $pimage = $(".panel-image");
    $(".panel").mouseenter(function () {
        $pimage.css('background-position', $(this).data('imagebp'));
    });
});

Note: There is no need to use hover() here as you are not doing anything in mouse leave event, so you can just register the mouseenter handler


Need Your Help

vstest.console.exe not generating Test Attributes (Owner, Priority, TestCategory) in .trx file

unit-testing visual-studio-2013 mstest vstest trx

I have test methods which are given attributes like Owner, Priority, TestCategory as follows