Reputation: 179
I'm trying to use CSS and javascript to fade in and out different colours for a div using multiple buttons and I got the code to work in codepen but when I tried to use it on the website it didn't work and I'm not sure why, the code is as follows:
$('.btn').on('click', function() {
var valColor = $(this).val();
$('.change').css({
background: valColor
});
});
.change {
-webkit-transition: .6s ease;
-moz-transition: .6s ease;
-ms-transition: .6s ease;
-o-transition: .6s ease;
background-color: rgb(25, 65, 196);
height: 15px;
width: 15px;
background-color: rgb(25, 65, 196);
border-radius: 50%;
display: inline-block;
}
<div class="change">
</div>
</br>
<button value="rgb(31, 221, 97)" class="black btn">On</button>
<button value="rgb(221, 56, 30)" class="red btn">Off</button>
like I said it worked in codepen but when I exported it and tried to use it in an HTML document it didn't work, I have no idea what the issue is so sorry if it is obvious.
Upvotes: 1
Views: 96
Reputation: 39
As already mentioned you have to add jquery to your script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Besides that you might want to add the transition field without prefix and specifiy the color explicitly:
transition: background-color .6s ease;
Upvotes: 0
Reputation: 16261
Add Jquery script to your project in the <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is learn about Jquery:https://www.w3schools.com/Jquery/default.asp
$('.btn').on('click', function() {
var valColor = $(this).val();
$('.change').css({
background: valColor
});
});
.change{
-webkit-transition: .6s ease;
-moz-transition: .6s ease;
-ms-transition: .6s ease;
-o-transition: .6s ease;
background-color:rgb(25, 65, 196);
height: 15px;
width: 15px;
background-color: rgb(25, 65, 196);
border-radius: 50%;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="change">
</div>
</br>
<button value="rgb(31, 221, 97)" class="black btn">On</button>
<button value="rgb(221, 56, 30)" class="red btn">Off</button>
Upvotes: 1