How to get element from HTML sliding bar to a JavaScript variable - javascript

I have this working script. It simply loop through and Object and display
the object key in HTML as sliding bar.
jQuery(function($) {
$('#threshold').change(updateThreshold);
function updateThreshold () {
var thresholdIndex = parseInt($('#threshold').val(), 10);
$("#foldchange_threshold").html(foldchange_thresholds[thresholdIndex]);
};
var foldchange_thresholds = [];
var mydata = {"3":["c","d"], "3.5":["j","k"], "1.5":["a","b"], "2.5":["x","y"] };
Object.keys(mydata).sort().forEach(function(key) {
foldchange_thresholds.push(key);
});
$('#threshold').attr('max', foldchange_thresholds.length-1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<body>
<!-- Display the sliding bar -->
<input id="threshold" type="range" min="0" max="1" step="1" value="0" />
<br>
<!-- Show foldchange threshold -->
<div id="foldchange_threshold" style="display: inline-block; align:center;"></div>
</body>
</html>
What I want to do, as user move the sliding bar, I'd like to get the element.
I am looking at something like these lines. But not sure where to put it.
var userFCchoice = document.getElementsByName('foldchange_threshold');
console.log(userFCchoice);
So if user slide to the value 3 the console log should print it out. How can I go about it?

No need for external plugins for this, jQuery is enough - You can attach your own mousedown, mousemove,mouseup combination to read the range input while dragging around:
JSnippet DEMO - Input range live update while dragging
$(function() {
//Global variable that holds the value and updates while dragging.
var valueTemp = 0;
//Events functions:
var changeEvent = function(){
var thresholdIndex = parseInt($('#threshold').val(), 10);
$("#foldchange_threshold").html($(this).val());
};
var downEvent = function(){
$(this).bind('mousemove',moveEvent);
};
var moveEvent = function(){
//trigger the change or comment it and do what ever you want:
$(this).trigger('change');
//Store the value into a variable available by other functions as asked in the comments:
valueTemp = $(this).val();
console.log($(this).val());
};
var upEvent = function(){
$(this).unbind('mousemove');
};
//Bind events - mousemove is bind and unbind by the mousedown & mouseup events.
$('#threshold').change(changeEvent);
$('#threshold').mousedown(downEvent);
$('#threshold').mouseup(upEvent);
});
EDIT:
Afetr some comments here is an update with the working example that saves the value to a "global" variable while dragging:
JSnippet DEMO update - Input range live update while dragging update

Have you tried using .slider functionality?
I've made a little example of getting the value to console.log, in the example below I'm using the jquery-ui.min.js and jquery-ui.css so that you can use the .slider.
slide: -
This section will show the value as 3 in the console.log
change: - This section will show the value in foldchange_threshold as 3.5
storedElementValue - I've create this as a global variable to store the value of the ui.value for later use.
.css() - You can add the .css() to quickly add values of how you want to style the element or you could also use .addClass() to add a class to the slider and then you change the style in your css style sheet
// Global variable to store value of the slider element
var storedElementValue = 0;
$(function($) {
var foldchange_thresholds = [];
var mydata = {
"3": ["c", "d"],
"3.5": ["j", "k"],
"1.5": ["a", "b"],
"2.5": ["x", "y"]
};
Object.keys(mydata).sort().forEach(function(key) {
foldchange_thresholds.push(key);
});
$("#threshold").slider({
min: 0, // min value
max: foldchange_thresholds.length - 1, // max value
step: 1,
value: 0, // default value of slider
slide: function(e, ui) {
// Show console log of element value
console.log(ui.value);
storedElementValue = ui.value;
},
change: function(e, ui) {
var thresholdIndex = parseInt(ui.value, 10);
$("#foldchange_threshold").html(foldchange_thresholds[thresholdIndex]);
$("#foldchange_threshold_storedValue").html("Stored value for later use: " + storedElementValue);
}
}).css("width", "200px");
});
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<!doctype html>
<html>
<body>
<!-- Display the sliding bar -->
<div id="threshold"></div>
<br>
<!-- Show foldchange threshold -->
<div id="foldchange_threshold" style="display: inline-block; align:center;"></div>
<br>
<div id="foldchange_threshold_storedValue" style="display: inline-block; align:center;"></div>
</body>
</html>

Related

How do I access a particular child and its text using event.target?

Consider this HTML code:
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
And here's Script I'm trying:
<script>
$(document).ready(function(){
$("#container").click(function(e){
var a=e.target.children().text();
//I want to store the text in the paragraph (e.g. Paragraph 1, when I click the first div) in var a.
var b=e.target.childNodes[0].nodeValue;
//I want to store the text in the div (e.g. Text1, when I click the first div) in var b.
});
});
</script>
But it's not working. I know I've written something wrong. What is the correct way to access those texts using event.target property?
The problem with e.target is it could be either the c1 element or the pc1 element.
You can target the c1 element with the click event and then find the first child of the c1 and its value
$(document).ready(function() {
$("#container").on('click', '.c1', function(e) {
var text = this.firstChild.nodeValue.trim();
snippet.log(text);
});
//using a gloabl handler, they way you have used
$("#container").click(function(e) {
var text = $(e.target).closest('div').contents().first().text();
snippet.log('2: ' + text);
});
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
$(document).ready(function() {
$("#container").click(function(e) {
var a = $(e.target).children().text();
//I want to store the text in the paragraph (e.g. Paragraph 1, when I click the first div) in var a.
alert(a)
//I want to store the text in the div (e.g. Text1, when I click the first div) in var b.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="c1">Text1
<p class="pc1">Paragraph1</p>
</div>
<div class="c1">Text2
<p class="pc1">Paragraph2</p>
</div>
</div>
Add $() to make it jquery object then you can use .children()
Since you are after the e.target's text node as well as the nested <p>, using jQuery .contents() filter would be a better option.
$("#container").children().click(function(e) { // limit events to children of #container
var selectElm = $(e.target);
var a,b;
selectElm.contents().filter( function(index,node){ // filter through the contents of selected elm
if(index === 0 ){ // only takes values of the first node (text only)
selectElm.is('p') ? a = $(this).text() : b = $(this).text() ; // assign a and b vars
}
});
});
See Demo
...and the shorter version w/o using .contents(),
$("#container").children().click(function(e) { // limit events to children of #container
var a,b;
$(e.target).is('p') ? a = e.target.childNodes[0].nodeValue : b = e.target.childNodes[0].nodeValue ;
});

Changing a javascript variable inside a DIV using JQuery

Firstly - i'm not even sure if the syntax is correct, but what i'm trying to do is, i have a div showing an animated image sequence which picks a position using a variable.
I will eventually use JSON to feed the value being changed, but for now i'm just trying to understand how to use JQuery to change the variable. Here's the code:
<div id="noiseAnimDiv" style="float: center; background-color: #ffffff; ">
<script type="text/javascript" src="./animatedpng.js">
</script>
<script type="text/javascript">
var stoptheClock = 3;
noiseAnim = new AnimatedPNG('noise', './noise/noise0.png', 8, 50);
noiseAnim.draw(false);
noiseAnim.setFrameDelay(stoptheClock, 1000); //spin yet stay on value 3
</script>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(
function() {
$("#stoptheClock").val(6); //
}
);
</script>
Any help much appreciated
code is live btw at so you can at least see the animation seq
http://ashleyjamesbrown.com/fgbp/noise.htm
The AnimatedPNG library you are using only checks the variable's value once - when initialized. in your code, you are changing the value after initializing it.
$(document).ready(
function() {
$("#stoptheClock").val(6); //
}
);
Should be
function() {
stoptheClock = 6;
noiseAnim.draw(false);
noiseAnim.setFrameDelay(stoptheClock,1000);
}
You are not using JQuery for any useful cause in your code, therefore I have removed all of the Jquery parts.

Loop for generating html inputs to processingjs

I am trying to use html input fields to control a sketch. Now I want to make a loop to generate more then one input.
var uivars = {
tA: "40", // set initial values
tB: "10",
};
Then I refer to those variables in the sketch:
<script type="application/processing" data-processing-target="pjs">
void draw() {
background(255);
var a = uivars.tA;
var b = uivars.tB;
line(0,b,a,b);
}
</script>
Then I get the values from the input fields and update the uivar variable in the beginning:
<script type="text/javascript" >
$(document).ready(function(){
$("#word_textboxA").keyup(function () { // whenever text is entered into input box...
uivars.tA = $(this).val(); // update word variable,
});
$("#word_textboxB").keyup(function () { // whenever text is entered into input box...
uivars.tB = $(this).val();
});
$("#word_textboxA").val(uivars.tA); // initialize input textbox contents.
$("#word_textboxB").val(uivars.tB); // initialize input textbox contents.
});
</script>
And the inputs:
<div id="PVarray">
<input type="text" id="word_textboxA"/><br/>
<input type="text" id="word_textboxB"/>
<div/>
I am building a sketch using processing js and will have over 40 inputs. So I am looking for a way to make a loop for these steps.
No I've managed to generate a number of input fields putting this somewhere:
<!-- <script>
window.onload = initAll;
function initAll(){
for(var i = 0; i<=1; i++)
{
var c=document.getElementById('PVarray');
var input = document.createElement('input');
input.setAttribute('type','text');
input.setAttribute('size','1');
input.setAttribute('id','num'+(i+1));
input.setAttribute('value', 'id' );
//Adds first input to container
c.appendChild(input);
input = '';
}
document.getElementById("show").innerHTML = uivars.tA;
}
</script> -->
But I just cannot find a way to refer in the jquery part to the changing id's of the html inputs.
I am not a experienced programmer. I looked around to find the answer but this is just a difficult one for me. My sketch will need over 40 inputs. the loop should just generate the html inputs, set the initial variables, update the variables on inputchange and give the values to the sketch. The names of the inputs and initial values can be put in a array.
If I understand correctly, the solution is quite simple.
You tagged the question with "jQuery", so here is a jQuery solution.
$(document).ready(function () {
//This is the keyup event handler, attached below to all <input> elements
function updateUivars() {
uivars[this.id] = this.value;
}
//a jQuery-wrapped reference to the PVarray container
var $c = $('#PVarray');
//Loop through uivars properties to create <input> elements with :
// - id equal to the property (the key)
// - an initial value equal to uivars[key]
$.each(uivars, function(key, value) {
$('<input type="text" size="1" />').attr('id', key).val(value).appendTo($c).on('keyup', updateUivars);
});
});
EDIT
So now, for each univars property, there is one value and two pieces of associated text.
var uivars = {
Ins: [30, "Insulation", "kWh/m2/day"],
D: [40, "Deterioration", "%"],
AO: [10, "Azimuth Offset", "%"],
SD: [20, "Surface Deposits", "%"],
TC: [30, "Temperature", "DegC"]
};
The loop that creates the input elements clearly needs to be amended to cause the associated text to be displayed.
Maybe it is less clear that the keyup event handler also needs to be modified to store values back in element [0] of the appropriate array.
Something like this should do it :
$(document).ready(function () {
//This is the keyup event handler, attached below to all <input> elements
function updateUivars() {
uivars[this.id][0] = this.value;
}
//a jQuery-wrapped reference to the PVarray container
var $c = $('#PVarray');
//Loop through uivars properties to create an inner div containing:
// - a label for the property's name
// - an <input> elements with :
// * id equal to the property (the key)
// * an initial value equal to uivars[key][0]
// - a label for the property's units
$.each(uivars, function(key, arr) {
var $div = $('<div class="property"/>').appendTo($c);//inner block element
$('<label/>').text(arr[1]).appendTo($div);
$('<input type="text" size="3" />').attr('id', key).val(arr[0]).appendTo($div).on('keyup', updateUivars);
$('<label/>').text(arr[2]).appendTo($div);
});
});
If desired, the inner divs can be styled in CSS with a .property {...} directive.

Getting value of jQuery slider

html
<h1>HTML Slider Test</h1>
<div class="slider" data-max="100"></div>
<p>Your slider has a value of <span class="slider-value"></span></p>
<input type="button" value="send" class="send">
<div class="slider" data-max="400"></div>
<p>Your slider has a value of <span class="slider-value"></span></p>
<input type="button" value="send" class="send">
jQuery
var a = 0;
$(".slider").each(function() {
$(this).slider({
value : 5,
min : 1,
max : $(this).data('max'),
step : 1,
slide : function (event, ui) {
a = ui.value;
$(this).next().find('span.slider-value').html(ui.value);
}
});
});
$(".send").click(function () {
var c=$(".slider-value").text();
alert(c);
});
on clicking first button i want value of that alone..but i am getting the value of both sliders.
http://jsfiddle.net/5TTm4/1906/
$(".slider-value") is returning both fields. Use Refiners to get a specific one.
Example:
$(".slider-value").first()
$(".slider-value").last()
http://jsfiddle.net/5TTm4/1909/
Dynamic solution
Simply create the button and its click event on the fly (or attach to an inline button) when creating the slider.
var a = 0;
$(".slider").each(function() {
var slider = this;
$(slider).slider({
value : 5,
min : 1,
max : $(this).data('max'),
step : 1,
slide : function (event, ui) {
a = ui.value;
$(this).next().find('span.slider-value').html(ui.value);
}
});
var button = $('<button>send</button>');
$(button).click(function() {
alert( $(slider).slider("option", "value"));
});
$(slider).next().find('span.slider-value').after($("<br />"), button);
});
Demo
You need a way of identifying the slider value you want to take, which currently wasn't possible without hardcoding it: .prev().prev().find(...blabla), which is a bad way of doing it, since your structure might change.
I updated your jsfiddle to make it work and give an example of how to easily do this using a data attribute and an ID: http://jsfiddle.net/5TTm4/1908/
You basicly give the button a selector of what element it is 'bound' to: data-slider="#slider-value-2"
You also give the slider value an id that matches that selector: id="slider-value-2"
Modify the onClick function:
var $this = $(this);
var c=$($this.attr('data-slider')).text();
Now you have a flexible way of retrieving values and binding elements to the buttons without being dependent on the dom. I suggest using the same technique for binding the value elements to the slider itself.
While i'm at it: cache the value of $(this), it's faster and saves you a lot of scoping issues if you expand your code.
$(".slider").each(function() {
var $this = $(this);
$this.slider({
value : 5,
min : 1,
max : $this.data('max'),
step : 1,
slide : function (event, ui) {
a = ui.value;
$this.next().find('span.slider-value').html(ui.value);
}
});
});

using arctext jquery plugin to create dynamic arc of text using range tag

I like the create arctext dynamically so I used arctext jquery plugin and I used the range html tag to select the arc or curve in the text.
This is my html code
<label>Curve:</label>
<input type="range" name="value" id="value" min="-100" max="100" value="0" />
<p id="textvalue"> I wanna to be curve</p>
javascript code :
<script type="text/javascript">
$(function(){
$("#value").change(function () {
var newValue = $('#value').val();
changetext(newValue);
});
function changetext(newValue){
console.log(newValue);
var pos;
if(newValue>0)
pos=1;
else{
pos=-1;
$("#textvalue").hide();
$("#textvalue").show().arctext({radius:newValue, dir: pos});
}
}
});
</script>
But this code work for the first drag. But later on it keeps remains unchanged. The range value is keep on changing which I came to know by console.log.
I think you meant to have the $("textvalue").hide() stuff outside the braces of the if statement. Also the slider goes negative and the text only takes positive values. I took a look at this and the only way I could get it to work was to completely remove the element and replace it with a the different radius so,
$(function(){
$("#value").change(function () {
var newValue = $('#value').val();
changetext(newValue);
});
function changetext(newValue){
console.log(newValue);
var pos;
if(newValue>0)
pos=1;
else{
pos=-1;
}
var text = $("#textvalue").text();
$("#textvalue").remove();
$('body').append('<p id="textvalue">'+ text +'</p>');
$("#textvalue").arctext({radius:Math.abs(newValue), dir: pos});
}
});

Categories