Android Guy
Android Guy

Reputation: 25

change bg color of button on press

i know this question may sound stupid to you guys, but i am a beginner so need some expert help and i want to ask that is there anyway to change background-color of the button when pressed, i mean when clicked it changes to different background-color and when released sets to default (when pressed via mouse). i am trying but when i set function to trigger on "keypress" the function doesn't trigger but when i use "click" it works but doesn't change to default when released...please help me..

javascript/jquery:

function initAll(){
$("#submitBtn").on('keypress', sendMessage);
}

function sendMessage(){
    $("#submitBtn").css('background-color', 'Red');
}

html:

<input type="button" id="submitBtn" name="submitBtnnm" value="Send" />

Upvotes: 1

Views: 2849

Answers (5)

greduan
greduan

Reputation: 4938

Have you tried the following?:

$('document').ready(function() {
    $('#submitBtn').mousedown(function() {
        $('#submitBtn').css('background-color', 'Red');
    }).mouseup(function() {
        $('#submitBtn').css('background-color', 'Blue');
    });
});

Basically, when the user presses the button it turns red, and when the user stops pressing it it turns blue.

Hope this helps. :)

Upvotes: 0

Afshin
Afshin

Reputation: 4215

you should use css class like this and use jquery to add class to body tag when button click

.changeback{
background-color: #333333;
background-image: url('images/background9.jpg');
 }

and jquery code should be like this

$("#send").click(function(){
  $('body').addClass('changeback');
}):

Upvotes: 0

Zoltan Toth
Zoltan Toth

Reputation: 47687

You dont need JS - just the :active state

#submitBtn:active {
    background: red;
}

DEMO

Upvotes: 8

Horen
Horen

Reputation: 11392

Try the jQuery mousedown and mouseup functions: http://api.jquery.com/mousedown/ and http://api.jquery.com/mouseup/

$(document).ready(function(){
  $("button").mousedown(function(){
    $(this).css("background", "red");        
  });
  $("button").mouseup(function(){
    $(this).css("background", "green");        
  });    
});

http://jsfiddle.net/CdzSB/

Upvotes: 0

Hidde
Hidde

Reputation: 11961

I would do it the following way (easier to read in my opinion):

function initAll() {
   $("#submitBtn").click(sendMessage);
}

function sendMessage () {
   $("#submitBtn").css('background-color', 'red');
}

Make sure you call the code initAll() on $(document).ready(). Otherwise, the code might run when there are no matching elements on the page.

Comment if you need more advice!

Upvotes: 0

Related Questions