Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change button text on mouseover by jQuery

If the button text is "followed" and the user hovers over it I want the text to change to "unfollow" and change back to "followed" once the user stops hovering.

Button:

{%if follow%}
<button type="submit" id="status" class="button" value="True"><span>followed</span></button>

{%else%}
<button type="submit" id="status" class="button" value="False"><span>follow</span></button>

{%endif%}

jQuery:

<script>
$(document).ready(function(){
    $(".button").click(function() {
        var status = $("#status").val();
        var course = $("#course").html()

        //SECTION THAT I'M HAVING TROUBLE WITH
        if ($(".button span").html() == "followed") {
            $(".button").mouseover(function() {
            $(".button span").html() = "unfollow";
            }
        }

        $.ajax({
            type: "POST",
            url: "/follow",
            data: 'status=' + status + "&course=" + course,
            success: function() {
$(".button span").html($(".button span").html() == 'followed' ? 'follow' : 'followed');
$(".button").val($(".button").val() == 'True' ? 'False' : 'True');
}
        });
        return false;
    });
});
</script>

When I run this I get

405 Method Not Allowed

The method POST is not allowed for this resource. 

But when I remove the mouseover code it works. What's wrong with the mouseover code?

Edit: Updated jQuery that now works, outside of onclick code, with mouseout:

if ($(".button span").html() == "followed") {
$(".button").mouseover(function() {
    $(".button span").html("unfollow");
});
$(".button").mouseout(function() {
    $(".button span").html("followed");
});
}

Edit: Actually, with the code above, if the button is "followed" and I click it, the button text remains "followed". I think this is because the mouseout function is overriding the ajax success function that changes it to "follow". How do I override the "followed" mouseout function once I click the button?

like image 835
mango Avatar asked Dec 20 '22 19:12

mango


2 Answers

try the following, you were missing the ");" on your mouseover call, which was borking everything after that...

//SECTION THAT I'M HAVING TROUBLE WITH
if ($(".button span").html() == "followed") {

    $(".button").mouseover(function() {
        // Pass the new string into .html()
        $(".button span").html("unfollow");
    });
}
like image 58
erikrunia Avatar answered Dec 22 '22 07:12

erikrunia


$(document).ready(function(){
    $('#status').hover(function() {
        $(this).find('span').text('unfollow');
    }, function() {
        $(this).find('span').text('followed');
    });
});

Hope this can help. http://jsfiddle.net/sing0920/54yfg/

like image 32
Mr.Sing Avatar answered Dec 22 '22 09:12

Mr.Sing