2kan
2kan

Reputation: 95

jQuery hover not unhovering

My problem is that I have a button and when the user hovers their mouse over it, it should change text.. and when they hover out it should go back to how it was before.

Here's my jQuery

$(document).ready(function() {
    $("#followingbutton").hover (
        function() {
            $(this).replaceWith("<input type='submit' value='Unfollow' id='followingbutton' class='button red' />");
        },
        function() {
            $(this).replaceWith("<input type='submit' value='Following' id='followingbutton' class='button green' />");
    });
});

It's supposed to act like the twitter follow/unfollow button. Can anyone shed some light for me?

EDIT: Everything works fine, except it wont 'unhover'

Upvotes: 0

Views: 717

Answers (4)

Rodolphe
Rodolphe

Reputation: 1731

Why not something like that (untested):

$(document).ready(function() {
    $("#followingbutton").hover (
        function() {
            $(this).val('Unfollow')
                   .attr('class', 'button red');
        },
        function() {
            $(this).val('Following')
                   .attr('class', 'button green');
    });
});

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

It won't unhover because the event isn't bound anymore as you have replaced the element.

Just change the value and class instead:

$("#followingbutton").hover (
    function() {
        $(this).val('Unfollow').toggleClass('red green');
    },
    function() {
        $(this).val('Following').toggleClass('red green');
});

Example - http://jsfiddle.net/infernalbadger/ETVpK/1/

Upvotes: 1

red-X
red-X

Reputation: 5128

this is because your removing the element that has the event listener and than replace it with a similar element

give this a try:

$(document).ready(function() {
    $("#followingbutton").hover (
        function() {
            this.value = 'Unfollow';
            this.className = 'button red';
        },
        function() {
            this.value = 'Following';
            this.className = 'button green';
    });
});

Upvotes: 0

Filip
Filip

Reputation: 2522

Why don't you try doing something like this?

$(document).ready(function() {
    $("#followingbutton").hover (
        function() {
            $(this).removeClass('green').addClass('red').attr('value', 'Unfollow');
        },
        function() {
            $(this).removeClass('red').addClass('green').attr('value', 'Follow');
    });
});

Upvotes: 0

Related Questions