Reputation: 1816
I'm working on an input slider function. I have it successfully working with jQuery, but I want to do it with pure JS.
Here's a fiddle http://jsfiddle.net/PbED3/ . Code is as follows:
HTML
<div class="image">
<img src="http://s23.postimg.org/78bouskgb/tumblr_n381qg_QRTS1st5lhmo1_1280.jpg" />
</div>
<div class="slider">
<input type="range" id="slider" min="0" max="100" onchange="rangevalue.value=value" value="100"/>
<output id="rangevalue">100</output>
</div>
JS (jQuery)
$(function() {
$("#slider").change(function(e) {
$(".image").css("height", $(this).val() * 2 + "px");
});
});
As you an see, the function gets the input value from the slider and appends it to the image element as a CSS height value.
I want to do this without Jquery.
So far my function is this:
//Pure JS
var value = document.getElementById("#slider").value;
var image = document.getElementsByClassName('.image');
image.style.height= value + "px";
Upvotes: 0
Views: 109
Reputation: 807
Here is how it would work, the HTML:
<div class="image">
<img src="http://s23.postimg.org/78bouskgb/tumblr_n381qg_QRTS1st5lhmo1_1280.jpg" />
</div>
<div class="slider">
<input type="range" id="slider" min="0" max="100" value="100"/>
<output id="rangevalue">100</output>
</div>
And the javascript:
var slider = document.getElementById("slider");
var rangevalue = document.getElementById("rangevalue");
var image = document.querySelector('.image');
slider.onchange = function () {
image.style.height = (slider.value * 2) + 'px';
rangevalue.value = slider.value;
};
The thing with your code is that you are using CSS selector terminology with document.getElementById
, which just needs the id of the element. If you want to use CSS selectors as you do with jQuery then use document.querySelector
(grabs the first element that corresponds to the selector) or document.querySelectorAll
. And also, you needed to place your callback inside an onchange
event handler of the slider element.
Upvotes: 3
Reputation: 35803
You were getting there, here is a working example without jQuery:
var slider = document.getElementById("slider");
if (slider.addEventListener) {
slider.addEventListener("change", slideHandler, false);
} else {
slider.attachEvent('onchange', slideHandler);
}
function slideHandler() {
var value = slider.value;
var image = document.getElementsByClassName('image')[0];
if (image) {
image.style.height= value + "px";
}
}
Main issues were than you needed to bind the event (addEventListener
or attachEvent
) and you were still passing jQuery style selectors to the getElementById
and getElementsByClassName
functions. Also, getElementsByClassName
returns an array so you only want to update the first instance found.
Upvotes: 0