Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="https://jariz.github.io/vibrant.js/dist/Vibrant.js"></script>
</head>
<body>
How to get the console result in the input fields below?
</br>
<label>1st<label>
<input value="" id="1"></br>
<p></p>
<label>2nd<label>
<input value="" id="2"></br>
<p></p>
<label>3rd<label>
<input value="" id="3"></br>
<p></p>
<label>4th<label>
<input value="" id="4"></br>
<p></p>
<label>5th<label>
<input value="" id="5"></br>
<div class="row examples">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<img data-src="examples/3.jpg">
</div>
</div>
</div>
<script>
var img = document.createElement('img');
img.setAttribute('src', 'examples/octocat.png')
img.addEventListener('load', function() {
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch])
console.log(swatch, swatches[swatch].getHex())
/*
* Results into:
* Vibrant #7a4426
* Muted #7b9eae
* DarkVibrant #348945
* DarkMuted #141414
* LightVibrant #f3ccb4
*/
});
</script>
</body>
</html>
My console perfectly returns
* Vibrant #7a4426
* Muted #7b9eae
* DarkVibrant #348945
* DarkMuted #141414
* LightVibrant #f3ccb4
The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.
Take a look at this example I made. Hopefully it helps!
var url = 'https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D';
var img = document.createElement('img');
img.setAttribute('src', url + '&' + new Date().getTime());
img.setAttribute('crossOrigin', '');
img.addEventListener('load', function() {
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches()
var i = 0;
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
document.getElementById(""+(i+1)).value = swatches[swatch].getHex();
i = i + 1;
}
});
<script src="https://jariz.github.io/vibrant.js/dist/Vibrant.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-sm-6">
<label>Vibrant</label>
<input value="" class="form-control" id="1">
<label>Muted</label>
<input value="" class="form-control" id="2">
<label>DarkVibrant</label>
<input value="" class="form-control" id="3">
<label>DarkMuted</label>
<input value="" class="form-control" id="4">
<label>LightVibrant</label>
<input value="" class="form-control" id="5">
</div>
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-body">
<img class="img-responsive" src="https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D">
</div>
</div>
</div>
</div>
</div>
Also you can find it here:
https://jsfiddle.net/bgmpow5q/
I am taking this approach (different for loop from yours) because I need to capture the input box;
luckily you have it as 1,2,3,4,5;
so I am using the index in interation; this index-in-iteration is difficult in a for-in structure;
hope this helps u.
for(i=1;i<=swatches.length;i++) {
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) let hexValue = swatches[swatch].getHex();
if (hexValue != undefined) {
document.getElementById(i).value = hexValue;
}
}
You can try something like following
for (var i=0; i< swatches.length; i++)
if (swatches.hasOwnProperty(swatches[i]) && swatches[i]){
document.getElementById(""+(i+1)).value = swatches[i].getHex();
console.log(swatches[i], swatches[i].getHex())
}
Related
I am a Java Script beginner and would like to pass the id of an image to an HTML file. When I click on a link I want to get to a page (annotator) with the image.
This is the Js part:
link = changeIIIFInformation(iiif, 10, "default")
var figure = document.createElement('figure')
var figcaption = document.createElement('figcaption')
var linkToImage = document.createElement('a')
linkToImage.setAttribute('href', 'annotator')
linkToImage.innerHTML = label;
figcaption.appendChild(linkToImage);
var image = document.createElement('img');
image.setAttribute('src', link);
figure.appendChild(image)
figure.appendChild(figcaption)
div.appendChild(figure)
count += 1;
if (count >= max_num + offset) {
break;
}
And this is the HTML Code:
<div class="container-fluid">
<div class="row">
<div class="col-md-6" role="main">
Tablet:
<select id="images" onchange="loadVariants()"></select>
Side:
<select id="imageside" onchange="reinit(null)"></select>
<button id="saveAnnotations" onclick="saveTextAsFile(JSON.stringify(curanno),'json','anno')">Save Annotations</button>
<button id="saveInGit" onclick="commitData()">Save Annotation in Gitlab</button>
<button id="showTransliteration" onClick='document.getElementById("transliterationdialog").show();'>Show Transliteration</button>
<button id="showTranslation" onClick='document.getElementById("translationdialog").show();'>Show Translation</button>
<button id="showPaleoCode" onClick='document.getElementById("paleocodedialog").show();'>Show PaleoCodes</button>
<button id="showIndexedChars" onClick="highlightIndexedChars()">Highlight Indexed Chars</button>
<button onclick="showHideAnno()">Show/Hide Annotations</button>
<br/>
Tagsets: CharacterSet: <input type="radio" id="characterset">
LinguisticAnnotation: <input type="radio" id="linguisticset" />
</div>
</div>
</div>
Here, I have a nice autocomplete dropdown that, given a city typed by the user, the page will show all possible city-state-country triplets. For example the name Guadalajara would suggest
Guadalajara de Buga, Valle del Cauca Department, Colombia
Guadalajara, Castilla La Mancha, Spain
and
Guadalajara, Jalisco, Mexico
The code works perfectly from both the backend and the frontend, the only problem left is that the autosuggest drop down menu will only work with the mouse and not with the keyboard. The Up and Down arrow keys will not allow to navigate through the most appropriate choice and pressing esc doesn't cancel the menu.
I tried everything and I have no idea about what is missing to make this work with the keyboard as well. I would like to find a solution with pure vanilla JavaScript and that would involve the least possible changes in the rest of working code. Here the entire code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vanilla Javascript Cities Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.8.2/css/bulma.min.css">
</head>
<body id="body">
<div class="title has-text-centered" id="main"></div>
<section id="form" class="section" onclick="clearCities()">
<div class="container">
<h1 class="title">Vanilla Cities Javascript</h1>
<!-- Row for City, State and Country -->
<div id="location">
<div class="field">
<div class="control">
<div id="cities-dropdown" class="dropdown">
<div class="dropdown-trigger">
<input name="cities" id="cities" onkeyup="getCities()" maxlength="50" class="input" type="text" placeholder="Enter a city" aria-haspopup="true" aria-controls="dropdown-menu3" -autocomplete="off" required
>
</div>
<div class="dropdown-menu" id="dropdown-menu3" role="menu">
<div id="cities-dropdown-content" class="dropdown-content">
<!-- content -->
<a class="dropdown-item"></a>
</div>
</div>
</div> Clear
</div>
<span class="is-size-7 has-text-info">(If your location doesn't appear immediately, try to type slower).</span>
</div>
<!-- City Field -->
<div class="field">
<div class="control">
<input name="city" id="city" class="input" type="text" placeholder="City" required>
</div>
</div>
<!-- State Field -->
<div class="field">
<div class="control">
<input name="state" id="state" class="input" type="text" placeholder="State" required>
</div>
</div>
<!-- Country Field -->
<div class="field">
<div class="control">
<input name="country" id="country" class="input" type="text" placeholder="Country" required>
</div>
</div>
</div>
</div>
</section>
</body>
<script>
function getCities(){
var inputCity = document.getElementById('cities').value;
const city = changeCase(inputCity);
if(city.length <= 2){
return false;
}
// Create request to get cities locations
var request = new XMLHttpRequest();
request.addEventListener("load", transferComplete);
request.open("GET", "/cities/?cityname=" + city);
request.send();
// Called when transfer is complete
function transferComplete(event){
//alert(event.srcElement.response);
locations = JSON.parse(event.srcElement.response);
// Return false if no matching city was found
if(locations.length == 0){
return false;
}
// Append choices
dropContent = document.getElementById('cities-dropdown-content');
dropContent.innerHTML = "";
for (var i = 0; i < locations.length; i++) {
var link = document.createElement("a");
link.setAttribute("onclick", "setCity(" + JSON.stringify(locations[i].name) + "," + JSON.stringify(locations[i].state) + "," + JSON.stringify(locations[i].country) + ")");
link.setAttribute("class", "dropdown-item");
link.innerHTML = locations[i].name + ", " + locations[i].state.name + ", " + locations[i].country.name
dropContent.append(link);
}
document.getElementById("cities-dropdown").classList.add("is-active");
}
// document.getElementById("products-list").innerHTML = html;
}
function setCity(city, state, country){
document.getElementById('cities').value = city+', '+state.name+', '+country.name;
document.getElementById('city').value = city;
document.getElementById('state').value = state.name;
document.getElementById('country').value = country.name;
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function clearCities(){
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function deleteEntry(e){
e.preventDefault();
document.getElementById('cities').value = '';
}
function changeCase(inputCity){
return inputCity
.replace(/([a-z])([A-Z])/g, function (allMatches, firstMatch, secondMatch) {
return firstMatch + " " + secondMatch;
})
.toLowerCase()
.replace(/([ -_]|^)(.)/g, function (allMatches, firstMatch, secondMatch) {
return (firstMatch ? " " : "") + secondMatch.toUpperCase();
}
);
}
var eraser = document.getElementById("clear");
eraser.addEventListener('click', deleteEntry);
</script>
I hope to find the simpler and least invasive solution to complete a code that just have this left.
I would change your dropdown and input to the semantic html datalist element:
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
Then both search and keyboard accessibility should work more or less out of the box.
If you really don't want to do that, you have to attach event listeners (vanilla js) to the different elements of your dropdown and input field and write a rather long thing to be able to tab or arrow key your way down and up and back into the search field. I would say it's too much work compared to the reward.
Better to use some time to css-animate the datalist so it behaves a bit smoother and style it neatly.
I have created an Add / Remove input fields. I want to get total of 'Amount' using Javascript which should not exceed 100%. Means the total of amount should not exceed 10000.
Say for example first field will have 3000, second will have 6000 and third will have 1000. If we enter larger number it should not accept it.
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="fund-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="allocate_amount[]" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-default">
<div class="panel-heading">
<center><b>Allocation of Funds</b></center>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-5">
<label>Allocation Items <b style="color:#FF0000;">*</b></label>
</div>
<div class="col-md-5">
<label>Amount <b style="color:#FF0000;">*</b></label>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]" placeholder="">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_amount[]" placeholder="">
</div>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add
</button>
</div>
</div>
<div id="fund-allocation-fields"></div>
<p class="help-block"><i>Total amount must be equal to the goal amount.</i></p>
</div>
</div>
Please Help me. Thanks in advance.
If I understand correctly you could do something as simple as:
var val1 = document.getElementById('inputOne').value;
var val2 = document.getElementById('inputTwo').value;
var val3 = document.getElementById('inputThree').value;
if(val1+val2+val3 < 10000){
// Less then 10000 so do your stuff
} else{
// More then 10000 so let the user know they went too far
}
You can also do it in jQuery. Just change document.getElementById('inputOne').value to $('#inputOne').val()
If the elements are built dynamically you could just do something like this:
var inputs = Array.from(document.querySelectorAll('.inputsToAdd'));
var number = 100;
document.getElementById('btn').addEventListener('click', ()=>{
inputs.map(input=>{
number+=parseInt(input.value);
})
if(number<10000)
console.log(true);
else console.log(false)
})
This is a bit of a connundrum since you have the ability to add infinite input fields, in common practice this is a bad UI experience but to resolve your issue.
You want to sum all the values on click and if the values are too high throw an error. You can accomplish this by assigning each inputField a class and then summing the collection of that class.
I made a small sample using jQuery, a conditional and .each() like so:
$('#sum').click(function(){
var nums = 0
$('.valueField').each(function(){
nums += parseInt(this.value)
});
nums > 10000 ? console.log("value too high", nums) : console.log("compute works", nums)
})
See my small demo below:
$('#sum').click(function() {
var nums = 0
$('.valueField').each(function() {
nums += parseInt(this.value)
});
nums > 10000 ? alert("value too high", nums) : alert("compute works", nums)
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type='number' class='valueField' />
<input type='number' class='valueField' />
<input type='number' class='valueField' />
<button id='sum'>Click</button>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
I would like to create similar calculator like here. It calculates the volume of a mulch. Visitor inserts three numbers: width, length and height (thickness) and it tells how much it has to buy.
html:
<form method="post" accept-charset="UTF-8">
<div class="form_area">
<div class="form_fields">
<div class="form_field ">
<label class="form_field_label">Width (m)</label>
<input type="text" value="" name="laius" id="laius" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Length (m)</label>
<input type="text" value="" name="pikkus" id="pikkus" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Thickness (cm)</label>
<input type="text" value="" name="paksus" id="paksus" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Total (m<sup>3</sup>)</label>
<input type="text" value="" readonly name="kokku" id="kokku" class="form_field_textfield form_field_size_small">
</div>
</div>
<div class="form_submit">
<input type="submit" value="Arvuta" id="calc_submit" name="commit">
</div>
</div>
</form>
javascript:
! function($) {
$(function() {
$("[rel='calc']").arvutus();
});
$.fn.arvutus = function() {
var inputs = $(this);
var kokku = $("#kokku:first");
inputs.bind("change keyup", function() {
var obj = $(this);
if (obj.val() !== "") {
parseFloat(obj.val()).toFixed(2);
};
arvuta();
});
$("#calc_submit").bind("click", function(e) {
e.preventDefault();
arvuta();
});
function arvuta() {
var width = inputs.filter("#laius").val();
width = width.toString();
width = width.replace(",", ".");
var lenght = inputs.filter("#pikkus").val();
lenght = lenght.toString();
lenght = lenght.replace(",", ".");
var thickness = inputs.filter("#paksus").val();
thickness = thickness.toString();
thickness = thickness.replace(",", ".");
thickness = thickness / 100;
var sum = width * lenght * thickness
sum = sum.toFixed(2);
kokku.val(sum + " m3 multši.");
};
};
}(window.jQuery);
I inserted html and javascript into jsfiddle, but mine doesn't work. Probably i miss something very obvious. some more javascript?
update: a little while ago, somebody provided a working code, but moderator removed it so quickly i couldn't copy it... :(
The code parseFloat(obj.val()).toFixed(2) returns a value, but you're not doing anything with it. Should it be stored somewhere so you can use it in calculating the volume?
I create a div and its css id like this.
<div id="r1" class="ansbox"></div>
<div id="r2" class="ansbox"></div>
<div id="r3" class="ansbox"></div>
<div id="r4" class="ansbox"></div>
<div id="r5" class="ansbox"></div>
<div id="r6" class="ansbox"></div>
<div id="r7" class="ansbox"></div>
<div id="r8" class="ansbox"></div>
<div id="r9" class="ansbox"></div>
<div id="r10" class="ansbox"></div>
is there a way to create this div using looping statement. Anyone help me..
I would recommend using some javascript (without jquery) for performance:
var toAdd = document.createDocumentFragment();
for(var i=0; i < 11; i++){
var newDiv = document.createElement('div');
newDiv.id = 'r'+i;
newDiv.className = 'ansbox';
toAdd.appendChild(newDiv);
}
document.appendChild(toAdd);
This way you only make one append(), only 1 reflow, and you don't need jQuery.
To append it to a jQuery selector:
$('sel').append(toAdd);
Or a dom element:
document.getElementById('sel').appendChild(toAdd);
Suppose you have following div where you will insert new divs:
<div id="target">
<!-- all divs will append here -->
</div>
jQuery:
for(var i =1; i<= 10; i++){
$('#target').append($('<div/>', { id: 'r' + i, 'class' : 'ansbox'}))
}
or
for(var i =1; i<= 10; i++){
$('#target').append('<div id="r'+ i +'" class="ansbox"></div>')
}
I will go for first approach.
Related refs:
.append()
Here's one option:
for(var i = 0; i <=10; i++) {
$('<div id="r'+i+'" class="ansbox"></div>').appendTo("target");
}
<div class="ibox-content" id="location-div">
<div class="row">
<div class="col-sm-12">
<button id="addlocation" type="button" class="btn btn-w-m btn-primary pull-right">Add new location</button>
</div>
</div>
<div class="row" style="margin-top:10px;">
<div class="col-sm-2">
<label class="form-label">Location <span ><input type="text" readonly id="locval" style="width:20px;border:0px;" value="1"></span></label>
</div>
<div class="col-sm-10">
<input type="text" name="" class="form-control ">
</div>
</div>
</div>
Here I want to add a dynamic row by adding 1 to each new entry this will solve your problem
<script>
$(document).ready(function(){
var inno = document.getElementById("locval").value;
for(var start = 1; inno >= start; start+=1)
{
start;
}
$("#addlocation").click(function(){
$("#location-div").append('<div class="row" style="margin-top:10px;"><div class="col-sm-2"><label class="form-label">Location <span ><input type="text" readonly id="locval" style="width:20px;border:0px" value="'+start+++'"></span> </label></div><div class="col-sm-10"><input type="text" name="" class="form-control "></div></div>');
});
});
</script>
I would recommend using simple javascript loop (without jquery) for performance:
let container = document.getElementById('container');
for (let i = 0; i <= 10; i++) {
let element = document.createElement('div');
container.appendChild(element);
};
console.log(container);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Answer</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
let container = document.getElementById('container');
for (let i = 0; i <= 10; i++) {
let element = document.createElement('div');
container.appendChild(element);
};