Search code examples
javascriptjqueryhtmlsimulate

Make HTML button appear pressed with JavaScript?


How can I make an HTML button looks like pressed via JavaScript?

I have a button that is sending a network message while pressed and sending another network message when released.

This specific named button may be displayed on more than once in a page or more than one device. So, if any of the identical purpose buttons pressed, I need to make the rest of the copies look like pressed.

How can I achieve that behaviour?


Solution

  • Personally I think it would be an overkill to use JavaScript for this, this done using CSS. Your code would go between the { }.

    button:active {
        color: red;
        background-color: pink;
        padding: 8px;
    }
    

    Warning!

    This will style all the button elements, not just one. If you'd like one only then use an ID, if more than one use class.

    http://jsfiddle.net/cp4bob0z/

    Edit 1

    JS Only

    <button id="test" onclick="styleButton(this);">Hello!</button>
    
    function styleButton(element) {
         document.getElementById(element.id).className = "yourClassName";
    }