Creating Multiple sliders using rangeslider.js plugin - javascript

I am working on a photo editing page. The goal is for users to be able to adjust parameters such as hue, saturation, brightness by uploading pictures and then editing them using range sliders. In order to ensure the program worked well on mobile browsers I decided to use the rangeslider.js library. After getting an initial slider up and working I decided to try more advanced designs. I found this design online and like it. My goal now is to have multiple slider each which displays its value like the linked slider. I am having trouble achieving this. To keep things simple I am currently formatting my slider using the standard css from rangeslider.js. I am able to create a single slider which behaves like the one in the linked design, but now I want to generalize this to multiple sliders, which is where I am having trouble. In the single design the code relevant to creating the rangeslider is
//custom slider javascript
var $element = $('input[type="range"]');
var $handle;
$element
.rangeslider({
polyfill: false,
onInit: function() {
$handle = $('.rangeslider__handle', this.$range);
updateHandle($handle[0], this.value);
}
})
.on('input', function() {
updateHandle($handle[0], this.value);
});
function updateHandle(el, val) {
el.textContent = " " + "$" + val + " ";
}
$(document).ready(function(){
//when slider changes, hide start message
$("input").on("change", function() {
$("#helper").fadeOut("slow");
});
//promo-box
$("#js-promo-box").hide();
$("#promo-link").on("click", function(){
$("#js-promo-box").slideToggle();
return false;
});
});
If I leave this function unchanged when declaring multiple range sliders in the html code then there are no errors but only the range input which was declared last will have a label displaying its value. But all of the sliders will be able to change this value. I narrowed this problem down to the fact that there is only a single $handle variable. To fix this I created the code below
<script>
//custom slider javascript
var $element = $('input[type="range"]'); // Gets all the elements of type range
var $handle = new Array($element.length);
console.log($element);
for(i=0; i<$element.length;i++){
console.log($element[i]);
var $temp = $($element[i]);
$temp.rangeslider({
polyfill: false,
onInit: function() {
$handle[i] = $('.rangeslider__handle', this.$range);
updateHandle($handle[i][0], this.value);
}
})
.on('input',function() {
updateHandle($handle[i][0], this.value);
});
}
function updateHandle(el, val) {
console.log(el);
el.textContent = " " + "$" + val + " ";
}
$(document).ready(function(){
//when slider changes, hide start message
$("input").on("change", function() {
$("#helper").fadeOut("slow");
});
//promo-box
$("#js-promo-box").hide();
$("#promo-link").on("click", function(){
$("#js-promo-box").slideToggle();
return false;
});
});
</script>
Now $handler is an array with as many entries as there are range inputs. When run everything initializes fine and the initial values of the sliders are displayed as expected. Despite this when I change the slider I get the error "Uncaught TypeError: can't access property 0, $handle[i] is undefined". This occurs in
.on('input',function() {
updateHandle($handle[i][0], this.value);
});
I do not understand why this error is occurring, especially since the values are initially displayed. Considering the only difference between the code for a single slider and multiple sliders is the $handle is now an array I believe it must have something to do with this but I am unsure where exactly the issue is.
Thank You

It turns out that this is a variable scope problem more than anything. An incredibly useful resource to explain this problem and its solution is "JavaScript Callbacks Variable Scope Problem" by Itay Grudev.
Essentially because the callback variable is created in a for loop use of the variable i (the looping variable) is not a good idea. This is because on later calls the value of i is not known to the callback function because it is outside of its scope. There are multiple ways to fix this as described by Itay Grudev. The easiest is to change
for(var i=0; i<$element.length;i++){ ...
Into
for(let i=0; i<$element.length;i++){ ...
But I believe this is not supported on all browsers. Instead what I did was create an inline closure. This allows me to create a variable within the closure which contains the value of i for a specific slider. In this way each callback can know which slider it corresponds to and react accordingly. My final code is below
for(var i=0; i<$element.length;i++){
console.log($element[i]);
var $temp = $($element[i]);
$temp.rangeslider({
polyfill: false,
onInit: function() {
//On init this is fine I don't need a separate definition of i
$handle[i] = $('.rangeslider__handle', this.$range);
updateHandle($handle[i][0], this.value);
}
})
.on('input', (function() {
var j = i;
return function() {
updateHandle($handle[j][0], this.value);
}
})() );
Now instead of calling a function to adjust the slider values this script creates a function to create a new function and then calls that function. The created function has access to variable j, which is what was missing previously

Related

Change thousands sign using JS

Here I would like to replace in the draggable slider the "," sign used for the thousands into this sign " ' " (a quote mark).
I am currently using a plugin to render the table (from a JSON file) so I cannot alter the HTML.
I am able to change the sign, in fact on page load the sign seems correct, but as soon I drag the slider the separator changes to a comma again.
I saw that the data is rendered from the Plugin with a comma in the aria-valuetext="" attribute: <div class="noUi-handle noUi-handle-upper" data-handle="1" tabindex="0" role="slider" aria-orientation="horizontal" aria-valuemin="0.0" aria-valuemax="100.0" aria-valuenow="100.0" aria-valuetext="2,290.00"><div class="noUi-tooltip">2,290.00</div></div>
I tried using this code without any results:
<script>
window.onload = function(){
var div = document.querySelectorAll('.noUi-tooltip');
div.forEach(function(r) {
var text = r.textContent;
var output = text.replace(/[,|]/g, "'");
r.innerHTML = output;
});
}
</script>
What am I writing wrong?
I am using WordPress and the wpdatatables plugin.
I'm not sure about the plugin you've used for your slider but perhaps you can try this for now:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == "attributes") {
var parentEl = document.getElementsByClassName('noUi-handle-upper');
var childEl = parentEl.childNodes[0];
childEl.innerHTML = childEl.innerHTML.replace(',', '\'');
}
});
});
observer.observe(document.getElementsByClassName('noUi-handle-upper')[0], {
attributes: true,
});
It's using MutationObserver which is not supported by older browsers. You can read more about it at https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver.
This is because you modify the string just in the beginning (on load).
This is why the code works in the beginning but doesn't work later, because it runs once and then stops.
I don't know how to use WordPress or sliders, but I'd advise you to use an 'on value changed' command, so the text will change to whatever you want it to each time the slider's value is changed.
I will post this now but I'll review your code and will try to update this with more exact information later.

Returning empty string on a input that has a value

I have a date input in my page, which I'm using Daterangepicker framework to populate it.
Here is the code of how I start my page!
$(function(){
startSelectors();
var variaveis = returnInputVars();
var rede = variaveis[0];
var codLoja = variaveis[1];
var period = variaveis[2];
console.log('1.'+rede+' 2.'+codLoja+' 3.'+period);
});
function returnInputVars(){
var rede = $("#dropdown-parceria").val();
var codLoja = $("#dropdown-loja").val();
var periodo = $("#datepicker-range").val();
return [rede, codLoja, periodo];
};
The function startSelectors() is set to start my datepicker and other fields, which is working perfectly. After it, I create a var called "variaveis" to fill
with the values of each field because I will use then later (this functions also works perfectly at other scripts of my page).
Running the page, my console returns this:
The funny thing is, if I type at the console this, the value is shown, just while starting the script is does not work!
Anybody experienced something like this?
***UPDATE
Adding this script to my start function:
console.log($("#datepicker-range"));
The value is shown, but the second console.log don't:
EDIT 1. FIDDLE (Suggested by #halleron)
To ensure things are loaded in the correct order, it is useful to apply a page sniffer code snippet that will scan the page continuously until a condition is met, or until a preset counter limit is reached (to prevent strain on browser memory). Below is an example of what I typically use that would fit your scenario.
I think because you are dealing with asynchronous loading, you can't have a global variable that holds the values in a global scope without an interval to detect when it can be used. Otherwise, it will attempt to read the variable when it is not yet ready.
You can invoke functions anywhere you like. But I would keep all of your variables contained within the page_sniffer_2017() because that is a controlled environment where you know that everything successfully loaded and you know that the variables are ready to be accessed without error.
That way, regardless of connection speed, your functions will only fire when ready and your code will flow, sequentially, in the right order.
Within the ajax success options, always add a class to the body of the document that you can search on to determine if it has finished loading.
$(document).ready(function() {
page_sniffer_2017();
});
function page_sniffer_2017() {
var counter = 0;
var imgScanner = setInterval(function() {
if ($("#datepicker-range").length > 0 && $("#datepicker-range").val().length && jQuery('body').hasClass('date-picker-successfully-generated')) {
var periodoDatepicker = $("#datepicker-range").val(); // ok
console.log(periodoDatepicker); // ok
var variaveis = returnInputVars(replaceDate(periodoDatepicker)); // ok
console.log(variaveis[0], variaveis[1], variaveis[2]);
//startNewSelectors(variaveis);
// start ajax call
generateData(variaveis[0], variaveis[1], variaveis[2]);
clearInterval(imgScanner);
} else {
//var doNothing = "";
counter++;
if (counter === 100) {
console.log(counter);
clearInterval(imgScanner);
}
}
}, 50);
}

AngularJS infinite-scroll issue

I'm trying to use infinite-scroll to lazy load images. I'm getting the following error when it's called though:
TypeError: undefined is not a function
at handler (http://onfilm.us/ng-infinite-scroll.js:31:34)
Here's a very watered down look of what I have thus far.
function tagsController($scope) {
$scope.handleClick = function(tags) {
// Parse Tags
$scope.finished_tags = parsed_data;
};
$scope.$emit( 'handleEmit', { tags = $scope.finished_tags; });
};
function imagesController($scope,$http) {
var rows_per = 5;
$scope.$on('handleBroadcast', function(event, args) {
// Sort the images here, put them in matrix
// Example: matrix[row_number] = { picture1, picture2, picture3 }
$scope.data = matrix;
$scope.loadMore();
};
$scope.loadMore() = function() {
var last = $scope.images.length;
for ( var i = 0; i < rows_per; i++ ) {
$scope.images[last + i] = new Array();
$scope.images[last + i] = $scope.data[last + i].slice( 0 );
}
}
}
The rough idea is that the page loads the first time (w/ no tags) and get images from a PHP script. All of them. They are stored, and loadMore() is called which will populate $scope.images with 5 rows of images. It does, and they are loaded.
The line in that script is accessing $window.height and $window.scrollup. I'm still pretty green w/ Javascript, so feel free to lambast me if I'm doing something horribly wrong.
This is the broken version I'm testing with:
http://onfilm.us/test.html
Here is a version before the lazy loading was implemented, if seeing how the tags work will help. I don't think that's the issue here though.
http://onfilm.us/image_index.html
EDIT: I do think this is a problem w/ the ng-infinite-scroll.js script. The error is on line 31 (of version 1.0.0). It's telling me:
TypeError: undefined is not a function
It doesn't like $window apparently.
My JS Kung Fu is not really equipped to say why. YOu can see a literal copy/paste job from the simple demo here (with the error) onfilm.us/scroll2.html
By refering your site, It appears at first instance that your HTML-markup is not appropriate. You should move infinite-scroll to the parent of ng-repeat directive so that it will not make overlapping calls for each row generated. Please visit http://binarymuse.github.io/ngInfiniteScroll/demo_basic.html

Use jQuery to determine when Django's filter_horizontal changes and then get the new data

I have a filter_horizontal selector in my Django admin that has a list of categories for products (this is on a product page in the admin). I want to change how the product change form looks based on the category or categories that are chosen in the filter_horizontal box.
I want to call a function every time a category is moved from the from or to section of the filter_horizontal.
What I have now is:
(function($){
$(document).ready(function(){
function toggleAttributeSection(choices) {
$.getJSON('/ajax/category-type/', { id: choices}, function (data, jqXHR) {
// check the data and make changes according to the choices
});
}
// The id in the assignment below is correct, but maybe I need to add option[]??
var $category = $('#id_category_to');
$category.change(function(){
toggleAttributeSection($(this).val());
});
});
})(django.jQuery);
The function never gets called when I move categories from the left side to the right side, or vice versa, of the filter_horizontal.
I assume that $category.change() is not correct, but I don't know what other events might be triggered when the filter_horizontal is changed. Also, I know there are multiple options inside of the select box. I haven't gotten that far yet, but how do I ensure all of them are passed to the function?
If anyone can point me in the right direction I would be very grateful. Thank!
You need to extend the SelectBox.redisplay function in a scope like so:
(function() {
var oldRedisplay = SelectBox.redisplay;
SelectBox.redisplay = function(id) {
oldRedisplay.call(this, id);
// do something
};
})();
Make sure to apply this after SelectBox has been initialized on the page and every time a select box refreshes (option moves, filter is added, etc.) your new function will be called.
(Code courtesy of Cork on #jquery)
I finally figured this out. Here is how it is done if anyone stumbles on this question. You need to listen for change events on both the _from and _to fields in the Django filter_horizontal and use a timeout to allow the Django javascript to finish running before you pull the contents of the _from or _to fields. Here is the code that worked for me:
var $category = $('#id_category_to');
$category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
var $avail_category = $('#id_category_from');
$avail_category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
And this is how I get the contents of the _to field:
function getFilterCategoryIds() {
var x = document.getElementById("id_category_to");
var counti;
var ids = [];
for (counti = 0; counti < x.length; counti++) {
ids.push(x.options[counti].value);
}
return ids;
}
I know it was a convoluted question and answer and people won't come across this often but hopefully it helps someone out.

How to make variable accessible within jQuery .each() function?

This is and example of a frequent dilemma: how to make markup accessible inide this .each()?
I'm more interested in learning how to access outer variables from within a closure than I am in this specific issue. I could fix this problem by assigning markup from inside the each function, but I'd rather learn a more elegant way to handle this kind of problem.
// hide form & display markup
function assessmentResults(){
// get assessment responses
var markup = parseForm();
// show assessment results to user
$('#cps-assess-form fieldset').each( function() {
var q = $(this).find('.fieldset-wrapper');
var i = 0;
// hide form questions
q.slideUp();
// insert markup
$('<div>'+markup[i]+'</div>').insertAfter(q);
i++;
});
}
Read the docs, it already has an index!
.each( function(index, Element) )
No need for i
$('#cps-assess-form fieldset').each( function(index) {
var q = $(this).find('.fieldset-wrapper').slideUp();
$('<div/>').html(markup[index]).insertAfter(q);
});
The reason why yours is failing is the i is inside of the function so it is reset every iteration. You would need to move it outside of the function for it to work.

Categories