JQuery Select the first, second and third link in LI

Hi You have a menu that looks like this

<div id="products_menu" class="span-9 last">
 <ul>
   <li><a href="#">beauty</a></li>
   <li><a href="#">fragrence</a></li>
   <li><a href="#">at home</a></li>
 </ul>
</div>

I would like to use jquery to change the CSS background image of the main div based on the hover of one of the links.

for example, when the user hovers over the Beauty link, then change css bg-imge to x, and if the user hangs over the flavor, then chaneg css bg-image to y.

Any help would be great

thank

+3
source share
4 answers

Sitting here in the class, bored, I decided that it would be more useful for you and for everyone if there was a real solution, rather than "Add ID" and use the general jQuery solution, so we go.

, , , , [0] 1 , .

. - html.

var backgroundImages = ["path_to_bg_1", "path_to_bg_2", "path_to_bg_3", "path_to_bg_4"];
$("#products_menu li").hover(function () {
    $("#products_menu").css("background", "url("+backgroundImages[$(this).index()]+")")
}, function () {
    $("#products_menu").css("background", "url(PATH_TO_DEFAULT)")
})

, , jsfiddle http://jsfiddle.net/k8ywX/

+1

asawyer ...

$(document).ready(function () {
    var backgrounds = ["background1","background2","background3"];
    $("#products_menu ul li").hover(
        function(){
            var ind = $("#products_menu ul li").index(this);
            $(this).parent().parent().css({"background-image" : "url("+backgrounds[ind]+")"});
        },
        function (){
            $(this).parent().parent().css("background","");
        });
});
+1

HTML:

<div id="products_menu" class="span-9 last">
    <ul>
        <li><a href="#" data-bgcolor="orange">beauty</a></li>
        <li><a href="#" data-bgcolor="yellow">fragrence</a></li>
        <li><a href="#" data-bgcolor="pink">at home</a></li>
    </ul>
</div>

JavaScript:

$('a', '#products_menu').bind('mouseenter mouseleave', function(e) {
    var c = e.type == 'mouseenter' ? $(this).data('bgcolor') : '';
    $(this).closest('div').css('background-color', c);
});

Live demo: http://jsfiddle.net/simevidas/hcu3h/2/

+1
source

try something like this:

<div id="products_menu" class="span-9 last">
 <ul>
   <li class="a"><a href="#">beauty</a></li>
   <li class="b"><a href="#">fragrence</a></li>
   <li class="c"><a href="#">at home</a></li>
 </ul>
</div>
<script>
$("li.a").hover(function(){
     $("#products_menu").css("background-image", "url(/myimage.jpg)");
});

$("li.b").hover(function(){
     $("#products_menu").css("background-image", "url(/myimage1.jpg)");
});

$("li.c").hover(function(){
     $("#products_menu").css("background-image", "url(/myimage2.jpg)");
});

</script>
0
source

Source: https://habr.com/ru/post/1796119/


All Articles