Rich
Rich

Reputation: 512

Detecting a hover and changing an image with jquery

Is there a better way of doing the following ? I have a carousel which goes through five slides, and I have some buttons above it. If a button is hovered, I change to the corresponding slide in the carousel . It works, but I wondered, is this the correct approach in jQuery?

    $('#cat_0').mouseover(function() {
        $('#carousel > li').removeClass('selected');
        $('#slide_0').addClass('selected');
    });

    $('#cat_1').mouseover(function() {
        $('#carousel > li').removeClass('selected');
        $('#slide_1').addClass('selected');
    });

    $('#cat_2').mouseover(function() {
        $('#carousel > li').removeClass('selected');
        $('#slide_2').addClass('selected');
    });

    $('#cat_3').mouseover(function() {
        $('#carousel > li').removeClass('selected');
        $('#slide_3').addClass('selected');
    });

    $('#cat_4').mouseover(function() {
        $('#carousel > li').removeClass('selected');
        $('#slide_4').addClass('selected');
    });

thanks

Upvotes: 0

Views: 66

Answers (2)

Neel
Neel

Reputation: 11741

You can do as shown below:-

Jquery:-

$('.btn').mouseover(function() {
    alert("sfg");
        $('#carousel > li').removeClass('selected');
        $(this).addClass('selected');
    });

HTML :-

<input type="text" id="state" value="test" />
<input type="button" value="button1" class="btn"/>
<input type="button" value="button2" class="btn"/>
<input type="button" value="button3" class="btn" />
<input type="button" value="button4"  class="btn"/>

Demo :-

http://jsfiddle.net/avmCX/42/

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

$('[id^="cat_"]').mouseover(function() {
    $('#carousel > li').removeClass('selected');
    $('#slide_' + (this.id.substring(4))).addClass('selected');
});

Upvotes: 1

Related Questions