Reputation: 17
New to js and could use some help. I have been trying to change the color of the box after clicking the button blue. Can I just use js to change the box color or do I need some css magic?
$("#btn1").on("click", function() {
$("#box").animate({
height: "+=35px",
width: "+=35px"
}, "fast");
})
$("#btn2").on("click", function() {
$("box")({
backgroundColor: "blue"
});
})
$("#btn3").on("click", function() {
$("#box").fadeOut();
})
$("#btn4").on("click", function() {
$("#box").animate({
height: "150px",
width: "150px"
}, "fast");
$("#box").fadeIn(), "fast";
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<div id="box" style="height:150px; width:150px; background-color:pink; margin:25px;"></div>
<button id="btn1">Grow</button>
<button id="btn2">Blue</button>
<button id="btn3">Fade</button>
<button id="btn4">Reset</button>
Upvotes: 1
Views: 5189
Reputation: 43880
As Heretic Monkey hinted at missing code, as Guzz mentioned you are missing the method .css()
and as Rafv mentioned, your selector is wrong is it should be $('#box')
. I'll go one step further in the spirit of the code and animate the color change:
$("#box").animate().css({
backgroundColor: "blue"
}, 2500);
and more importantly add this to the CSS:
#box {
transition: background-color 2.5s ease-out
}
As a bonus, the reset function is rewritten so that the methods are chained and arranged so that each animation can be seen in reverse.
...
$("#box").fadeIn("fast").animate({
height: "150px",
width: "150px"
}, "fast").css({
backgroundColor: "pink"
}, 1500);
...
$("#btn1").on("click", function() {
$("#box").animate({
height: "+=35px",
width: "+=35px"
}, "fast");
});
$("#btn2").on("click", function() {
$("#box").animate().css({
backgroundColor: "blue"
}, 2500);
});
$("#btn3").on("click", function() {
$("#box").fadeOut();
});
$("#btn4").on("click", function() {
$("#box").fadeIn("fast").animate({
height: "150px",
width: "150px"
}, "fast").css({
backgroundColor: "pink"
}, 1500);
});
#box {
transition: background-color 2.5s ease-out
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<div id="box" style="height:150px; width:150px; background-color:pink; margin:25px;"></div>
<button id="btn1">Grow</button>
<button id="btn2">Blue</button>
<button id="btn3">Fade</button>
<button id="btn4">Reset</button>
Upvotes: 0
Reputation: 261
You missing #
in box
section and for non-multiple css, better use
$("#box").css("background-color", "blue");
css("propertyname","value");
More about this here.
Upvotes: 0
Reputation: 66
Your jquery function should be:
$("box").css({backgroundColor:"blue"});
Upvotes: 1