4
votes

The javascript jQuery code below works, except I would like to add 2 features to the button's state.

  1. When a user clicks one of the buttons, the other button that was not clicked gets a new class (look).

  2. Both button's state should change to unclickable.

[div id="1" class="__button_image"] [/div]
[div id="2" class="__button_image"] [/div]
$("div.__button_image").mouseover(function () {
    $(this).addClass("__button_image_hover");
});

$("div.__button_image").mouseout(function () {
    jq(this).removeClass("__button_image_hover");
});

$("div.__button_image").click(function () { 
    $(this).removeClass("__button_image_hover");
    $(this).addClass("__button_image_clicked");

    jQuery.get('/do/request');        
});
5

5 Answers

3
votes

Here is final code I went with:

$("div.__button_image").mouseover(function () {
    $(this).addClass("__button_image_hover");
});

$("div.__button_image").mouseout(function () {
    $(this).removeClass("__button_image_hover");
});

$("div.__button_image").click(function () {

    /** change button look to 'clicked' */
    $(this).addClass("__button_image_clicked");

    /** get the id of the current button */
    b_id = $(this).attr('id');

    /** unbind both vote buttons for *no* interaction */
    $("div.__button_image").unbind('click');
    $("div.__button_image").unbind('mouseover');
    $("div.__button_image").unbind('mouseout');

    /**
     * wire the .each function to iterate the classes 
     * so we can change the look of the one that was 
     * not clicked.
    */
    $('div.__button_image').each(function() {
      button_id = $(this).attr('id');
      if(button_id!=b_id) {
         $('#'+button_id).removeClass("__button_image");
         $('#'+button_id).addClass("__button_image_gray");  

    }
});

jQuery.get('/do/request?id='+b_id); 
$(this).parent().css('cursor', 'default');
2
votes

What's the problem? The only thing I can see that you're missing is

$("div.__button_image").unbind('click');

This will remove the 'click' handler (setting it back to the default).

1
votes

I would change your click() handler to this:

$("div.__button_image").click(function () { 
    $(this).removeClass("__button_image_hover");
    $(this).addClass("__button_image_clicked");

    /*
     * Add look class to all buttons, then remove it from this one
     */
    $("div.__button_image").addClass("look");
    $(this).removeClass("look");

    /*
     * Remove click handler from all buttons
     */
    $("div.__button_image").unbind('click');

    jQuery.get('/do/request');        
});
1
votes

This always works for me (also changes the opacity to 80% and changes the cursor to wait)

$("#buttonDivId").css({opacity: 0.8, cursor: "wait"}).prop("disabled", true);
0
votes

If you are using JQuery UI you can use the disable method.

$("selector").button("disable");

http://api.jqueryui.com/button/