Reputation: 2139
I am working through head first jquery and I am on a chapter dealing with the jquery ui. Specifically, the example is walking through a jquery slider that displays the value of that slider above the slider. Screenshot: https://i.sstatic.net/BMksn.png However, I am having great difficulty understanding the code:
THE HTML:
<h3>Distance from Creature (in ft.):</h3>
<input type="text" id="distance" class="just_display" name="creature_distance" readonly="readonly"/>
<div id="slide_dist"></div>
<h3>Creature Weight (in lbs.):</h3>
<input type="text" id="weight" class="just_display" name="creature_weight" readonly="readonly"/>
<div id="slide_weight"></div>
<h3>Creature Height (in ft.):</h3>
<input type="text" id="height" class="just_display" name="creature_height" readonly="readonly"/>
<div id="slide_height"></div>
THE JQUERY:
//3a. slide_dist
$( "#slide_dist" ).slider({
value:0,
min: 0,
max: 500,
step: 10,
slide: function( event, ui ) {
$( "#distance" ).val( ui.value);
}
});
$( "#distance" ).val( $( "#slide_dist" ).slider( "value" ));
//3b. slide_weight
$( "#slide_weight" ).slider({
value:0,
min: 0,
max: 5000,
step: 5,
slide: function( event, ui ) {
$( "#weight" ).val( ui.value);
}
});
$( "#weight" ).val( $( "#slide_weight" ).slider( "value" ));
//3c. slide_height
$( "#slide_height" ).slider({
value:0,
min: 0,
max: 20,
step: 1,
slide: function( event, ui ) {
$( "#height" ).val( ui.value);
}
});
$( "#height" ).val( $( "#slide_height" ).slider( "value" ));
I am seriously confused by the slide parameter in the slider method:
slide: function( event, ui ) {
$( "#height" ).val( ui.value);
}
From what I can tell, this is changing the value above the slider to match whatever the slider's value is. However, if that is the case, then what does the line following the slider method do:
$( "#height" ).val( $( "#slide_height" ).slider( "value" ));
Arent these lines doing the same thing? Any and all input would be appreciated.
Upvotes: 2
Views: 4319
Reputation: 126042
This line:
slide: function( event, ui ) {
$( "#height" ).val( ui.value);
}
Is defining an event handler for the "slide" event as defined by jQueryUI. The event handler updates #height
with the updated value of the slider on every mouse move during the slide.
This line (in the context you've given):
$( "#height" ).val( $( "#slide_height" ).slider( "value" ));
Is simply setting the value of #height
to 0
initially (the initial value of the slider is 0, you can see the value
option in each slider initialized to 0
with value:0
).
The difference between the two is that the first runs every time the mouse moves on the slider and the second is executed once immediately after the slider is initialized, providing an initial value for the #height
element (0
in this case).
Another way of looking at it is that if the second snippet wasn't there, the #height
element wouldn't show 0
initially (try removing that line to see what I mean).
Upvotes: 1