-1

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?

ceremcem
  • 3,900
  • 4
  • 28
  • 66

4 Answers4

1

You might want to add class to the button in your function.

$('button').addClass('someclass')

then just define your class using CSS.

Sachi Tekina
  • 1,800
  • 5
  • 28
  • 50
0

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";
}
Script47
  • 14,230
  • 4
  • 45
  • 66
  • This doesn't answer his question. He is asking how to make a button change to the `active` state via JavaScript. I don't believe this can be accomplished with just CSS (unless you mirror custom styles from `button:active`, but then it's still not truely in the active state). –  Aug 06 '15 at 02:34
  • @Jamen I answered the question to my best ability. If the OP decides to make his question clearer, I'll gladly update my post. – Script47 Aug 06 '15 at 02:37
  • @ceremcem added JS only solution. – Script47 Aug 06 '15 at 02:39
  • Thank you. I suppose there is no way to make it look like the original pressed style (except for making a fine tune with CSS). – ceremcem Aug 06 '15 at 02:48
0

In your CSS, style the active button like so:

button:ative, .active-class {

}

That way a clicked button will look the same as if it had the class active-class.

From here, you can apply / remove the class in any way you'd please...

$(".my-button").on("click", function(){
  $(this).toggleClass("active-class");
});

Example JSFiddle

0

The borderStyle style property can be set to do this. To show the button depressed, use

document.getElementById("myButton").style.borderStyle = "inset";

Once completed, use

document.getElementById("myButton").style.borderStyle = "outset";

to set the button back to normal.

Erik Anderson
  • 4,915
  • 3
  • 31
  • 30