3

I'm new to JQuery. I have a button with a css-class that is working fine, but I want to change the css-class when I hover the button.

How do I code this?

This is what I got so far:

//on top in my heading:

<script type="text/javascript">
    $('btn').hover(function () {
        alert("Test"); //just for testing
    });
</script>

//my button:

<button id="btn" class="default_btn">ButtonText</button> 

4 Answers 4

2

Why dont you try CSS?

.default_btn:hover{
    background-color: #f00;
}

Demo here: http://jsfiddle.net/naveen/Ytkma/

If you want jQuery Solution, try this.

$("#btn").hover(function() {
        $(this)
            .removeClass("default_btn")
            .addClass("default_hover_btn");
    }, function() {
        $(this)
            .removeClass("default_hover_btn")
            .addClass("default_btn");
});

Demo: http://jsfiddle.net/naveen/SfGVD/

Sign up to request clarification or add additional context in comments.

2 Comments

I know how to do it in CSS, but trying to learn JQuery and want to try to do it with that =)
You could use the toggle method for the class
1

Change reference to #btn.

$(document).ready(function(){

    $('#btn').hover(function () {
            alert("Test"); //just for testing
        });

});

See JSfiddle:

http://jsfiddle.net/Curt/CKXw3/1/

1 Comment

I missed the "#" before my button-id and forgot the (document).ready-part at the top.
0

Anyway, for your code to work, change your selector to

$('#btn')

Comments

0

If you want to select ID's in jQuery you simply to it as you do in css: #id, in your case #btn

The jQuery helper function hover normally needs to callbacks. one on mouse over and one on mouse out.

$(document).ready(function(){
    $('#btn').hover(function(){
        alert("over");
    },function(){
        alert("out");
    });
});

Another way is to detect the event type:

$(document).ready(function(){
    $('#btn').hover(function(event){
        if (event.type == "mouseenter") {
            console.log("over");
        } else {
            console.log("out");
        }
    });
});

The function hover binds to functions to the jQuery Object. mouseenter and mouseleave. Therefore we can assume if its not mouseenter it's mouseleave.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.