user2520410
user2520410

Reputation: 479

Start a CSS transition via JS does not work

I want to start a CSS transition, that changes the background-color and the dimension if a button is clicked. But there is a mistake in the code:

js fiddle

jQuery

$(function() {

$('#change').click(function() {
    $('#box').addClass('change');
});
});

HTML

<div id="box" class="start"></div>

<div id="button">click</div>

CSS

.start{

height:100px;
width:100px;
background: black;
transition: all 2.0s linear;
-webkit-transition: all 0.8s linear;
-moz-transition: all 0.8s linear;
-ms-transition: all 0.8s linear;
-o-transition: all 0.8s linear;
}

.change{
width: 200px;
height: 200px;
background:yellow;
}

#button{
width: 80px;
height: 20px;
padding: 4px;
margin: 5px;
border:solid 1px black;
 background: grey;
cursor: pointer;
color: white;
}

Upvotes: 0

Views: 128

Answers (3)

Ana
Ana

Reputation: 37178

The id of the button in the HTML & CSS (#button) is different from the id of the button in the JS (#change), that's why.

If you replace #change with #button in the JS, then it works.


Note: When you list transition rules for various browsers, you don't need the -ms- one (IE10 supports transitions unprefixed and IE9 does not support them at all; the -ms- prefix was only needed for early IE10 previews) and you should always put the unprefixed one last. At this point, all current versions of desktop browsers support transitions unprefixed.

Upvotes: 6

cpreid
cpreid

Reputation: 621

It should be using #button,

$(function() {
    $('#button').click(function() {
        $('#box').addClass('change');
    });
});

as per your HTML

<div id="button">click</div>

http://jsfiddle.net/qsAZQ/

Upvotes: 2

Michał Rybak
Michał Rybak

Reputation: 8706

Id of your button is button, not change.

Use $('#button') instead of $('#change').

DEMO HERE.

Upvotes: 2

Related Questions