Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAleem Mohamed
Courses Plus Student 7,011 Points.change(changeColor) vs .on("input change", changeColor)
Hello,
I've finished the lesson and implemented the slider however in Chrome, using the code provided the value for each slider does not change when you slide the slider. It only changes after you release the mouse button.
function changeColor() {
var r = $("#red").val();
var g = $("#green").val();
var b = $("#blue").val();
$("#newColor").css("background-color", "rgb(" + r + "," + g + "," + b + ")");
}
$("input[type=range]").change(changeColor);
However, when I use
function changeColor() {
var r = $("#red").val();
var g = $("#green").val();
var b = $("#blue").val();
$("#newColor").css("background-color", "rgb(" + r + "," + g + "," + b + ")");
}
$("input[type=range]").on("input", changeColor);
The slider works as a slider and the slider value changes as I drag the slider.
Does anyone know why this is happening?
2 Answers
Aleem Mohamed
Courses Plus Student 7,011 PointsI found an answer here:
http://stackoverflow.com/questions/12797700/jquery-detect-change-in-input-field
It seems as though the .change event only fires when the user deselects, or in my case, releases the mouse button. The value is then returned. Whereas it seems with .on the value gets updated "dynamically".
EDIT: Just to be clear the best answer was Jason Anello's reply to this.
Aleem Mohamed
Courses Plus Student 7,011 PointsWonderful. Thanks, Jason!
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi Aleem,
It's not the
.on
method that does this but rather the "input" event.The original could have been written like this:
$("input[type=range]").on("change", changeColor);
and it still wouldn't update until you released the slider.The "input" event goes off multiple times while you're dragging the slider. This is what allows it to continually update the preview color.
It had worked in the video because chrome had a bug at the time with how the "change" event worked. The "change" event was working the way the "input" event is supposed to work.
You may be interested in this: http://www.w3.org/TR/html5/forms.html#common-input-element-events
It explains when the "change" and "input" events should go off under various circumstances.