How do I add an image to an if statement in Javascript? - javascript

I'm new at JavaScript to be patient with me. I'm trying to get this little "game" to work where you drag cards in the drop box, and when you drop the joker card in it says "victory", otherwise it says "betrayal" for the other cards. Everything works great except the part where it says "victory" when you drop the joker. I feel like I have tried everything. The joker card is $(#black_joker)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop</title>
<link rel="stylesheet" href="dragdrop.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<h1>Find the Joker and eliminate him!</h1>
<br>
<input type="button" value="Deal!" id="dealDeck">
<br>
<br>
<br>
<br>
<br>
<div id='dropZone' class='dropZone'> <center>Find the joker card and drop it here to get rid of him once and for all! </center></div>
<script src="dragdrop.js"></script>
</body>
</html>
// JAVASCRIPT
$(document).ready(function () {
$(init);
function init() {
$('.dropZone').droppable({
drop: handleDropEvent
});
}
for (var a=0, all = 53; a < all; a++){
$('#dealDeck').click(function () {
dealCard(randomCard());
});
}
var cardsInDeck = new Array();
var numberOfCardsInDeck = 53;
cardsInDeck[0] = "C1";
cardsInDeck[1] = "C2";
cardsInDeck[2] = "C3";
cardsInDeck[3] = "C4";
cardsInDeck[4] = "C5";
cardsInDeck[5] = "C6";
cardsInDeck[6] = "C7";
cardsInDeck[7] = "C8";
cardsInDeck[8] = "C9";
cardsInDeck[9] = "C10";
cardsInDeck[10] = "C11";
cardsInDeck[11] = "C12";
cardsInDeck[12] = "C13";
cardsInDeck[13] = "D1";
cardsInDeck[14] = "D2";
cardsInDeck[15] = "D3";
cardsInDeck[16] = "D4";
cardsInDeck[17] = "D5";
cardsInDeck[18] = "D6";
cardsInDeck[19] = "D7";
cardsInDeck[20] = "D8";
cardsInDeck[21] = "D9";
cardsInDeck[22] = "D10";
cardsInDeck[23] = "D11";
cardsInDeck[24] = "D12";
cardsInDeck[25] = "D13";
cardsInDeck[26] = "H1";
cardsInDeck[27] = "H2";
cardsInDeck[28] = "H3";
cardsInDeck[29] = "H4";
cardsInDeck[30] = "H5";
cardsInDeck[31] = "H6";
cardsInDeck[32] = "H7";
cardsInDeck[33] = "H8";
cardsInDeck[34] = "H9";
cardsInDeck[35] = "H10";
cardsInDeck[36] = "H11";
cardsInDeck[37] = "H12";
cardsInDeck[38] = "H13";
cardsInDeck[39] = "S1";
cardsInDeck[40] = "S2";
cardsInDeck[41] = "S3";
cardsInDeck[42] = "S4";
cardsInDeck[43] = "S5";
cardsInDeck[44] = "S6";
cardsInDeck[45] = "S7";
cardsInDeck[46] = "S8";
cardsInDeck[47] = "S9";
cardsInDeck[48] = "S10";
cardsInDeck[49] = "S11";
cardsInDeck[50] = "S12";
cardsInDeck[51] = "S13";
cardsInDeck[52] = "black_joker";
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var img = document.createElement("img");
img.src = "http://deetito.com/images/" + cardsInDeck[i] + ".png";
img.id = cardsInDeck[i];
img.width = 100;
img.height = 125;
document.body.appendChild(img);
$('#C1').draggable();
$('#C2').draggable();
$('#C3').draggable();
$('#C4').draggable();
$('#C5').draggable();
$('#C6').draggable();
$('#C7').draggable();
$('#C8').draggable();
$('#C9').draggable();
$('#C10').draggable();
$('#C11').draggable();
$('#C12').draggable();
$('#C13').draggable();
$('#D1').draggable();
$('#D2').draggable();
$('#D3').draggable();
$('#D4').draggable();
$('#D5').draggable();
$('#D6').draggable();
$('#D7').draggable();
$('#D8').draggable();
$('#D9').draggable();
$('#D10').draggable();
$('#D11').draggable();
$('#D12').draggable();
$('#D13').draggable();
$('#H1').draggable();
$('#H2').draggable();
$('#H3').draggable();
$('#H4').draggable();
$('#H5').draggable();
$('#H6').draggable();
$('#H7').draggable();
$('#H8').draggable();
$('#H9').draggable();
$('#H10').draggable();
$('#H11').draggable();
$('#H12').draggable();
$('#H13').draggable();
$('#S1').draggable();
$('#S2').draggable();
$('#S3').draggable();
$('#S4').draggable();
$('#S5').draggable();
$('#S6').draggable();
$('#S7').draggable();
$('#S8').draggable();
$('#S9').draggable();
$('#S10').draggable();
$('#S11').draggable();
$('#S12').draggable();
$('#S13').draggable();
$('#black_joker').draggable();
removeCard(i);
}
function randomCard() {
return Math.floor(Math.random() * numberOfCardsInDeck);
}
function handleDropEvent(event, ui) {
var card = ui.draggable;
if (card == 'black_joker') {
$('#dropZone').html('victory!');}
else {
$('#dropZone').html('betrayal!');}
/*$('#dropZone').droppable({
drop: function(event, ui) {
ui.draggable.remove();
}
});*/
$("#dropZone").on('mouseover', function() {
//alert('bye draggable!');
//ui.draggable.draggable('disable');
//$(this).droppable('disable');
ui.draggable.remove();
})
}
function removeCard(c) {
// simply make every higher numbered card move down 1
for (j = c; j <= numberOfCardsInDeck - 2; j++) {
cardsInDeck[j] = cardsInDeck[j + 1];
}
numberOfCardsInDeck--;
}
});

I believe you are comparing object with string.
ui.draggable should be jQuery object
let card = ui.draggable.attr("id");
compare it with your id or other attribute you wanted to use should work

Related

Changing the SpeechSynthesis voice not working

I have tried all the variations I can find on stackoverflow, but I can still not get the voice to change on SpeechSynthesis
Below is the standalone code that fills a dropdown with all the available voices and allows me to select which voice I want.
Unfortunately this code does not change the voice. Also, before changing the voice. msg.voice is null, even though it has been used to list all the available voices.
Can anyone tell me what is wrong with the code? (console.log(msg.voice); gives a null before being set)
<!doctype html>
<html>
<head>
<SCRIPT>
var msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
var numberOfVoices=0;
function Main(){
voiceSelect=document.getElementById("voiceSelect");
setTimeout(getVoicesFunction,2000);
}
function getVoicesFunction(){
msg = new SpeechSynthesisUtterance("hello");
numberOfVoices=0;
speechSynthesis.getVoices().forEach(function(voice) {
var option = document.createElement('option');
option.text = option.value = voice.voiceURI;
voiceSelect.add(option, 0);
numberOfVoices=numberOfVoices+1;
});
voiceSelect.onchange = voiceChange;
}
function voiceChange(){
textToSpeech("this is the old voice");
var selectedOption = this[this.selectedIndex];
selectedVoice = selectedOption.text;
msg = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
msg = new SpeechSynthesisUtterance();
console.log("before change msg.voice");
console.log(msg.voice);
for(i = 0; i < numberOfVoices ; i++) {
if(voices[i].voiceURI === selectedVoice) {
var temp="changing the voice number to "+i;
setTimeout(textToSpeech,2000,temp);
msg.voice = voices[i];
console.log(msg.voice);
var tempVoiceNumber=i;
};
}
setTimeout(textToSpeech,4000,"this is the new voice");
}
function textToSpeech(tspeech){
msg = new SpeechSynthesisUtterance();
msg.text = tspeech;
speechSynthesis.speak(msg);
console.log("speech "+tspeech);
}
</SCRIPT>
</head>
<body onload= "Main()" id= "mainb">
<div id="container">
<select name="Combobox1" size="1" id="voiceSelect">
</select>
</div>
</body>
</html>
IanR, I copied the code and it works for me. I cut out the pitch and rate controls and made the html simpler, but it's basically the same.
If it doesn't work for you are you getting any console errors?
var synth = window.speechSynthesis;
var inputForm = document.querySelector('form');
var inputTxt = document.querySelector('.txt');
var voiceSelect = document.querySelector('select');
/*var pitch = document.querySelector('#pitch');
var pitchValue = document.querySelector('.pitch-value');
var rate = document.querySelector('#rate');
var rateValue = document.querySelector('.rate-value');*/
var voices = [];
function populateVoiceList() {
voices = synth.getVoices();
for (i = 0; i < voices.length; i++) {
var option = document.createElement('option');
option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
if (voices[i].default) {
option.textContent += ' -- DEFAULT';
}
option.setAttribute('data-lang', voices[i].lang);
option.setAttribute('data-name', voices[i].name);
voiceSelect.appendChild(option);
}
}
populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
speechSynthesis.onvoiceschanged = populateVoiceList;
}
inputForm.onsubmit = function(event) {
event.preventDefault();
var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
for (i = 0; i < voices.length; i++) {
if (voices[i].name === selectedOption) {
utterThis.voice = voices[i];
}
}
//utterThis.pitch = pitch.value;
//utterThis.rate = rate.value;
synth.speak(utterThis);
inputTxt.blur();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>61016951</title>
<script src="61016951.js" defer></script>
</head>
<body>
<div id="div">
<form>
<input type="text" class="txt">
<select></select>
<button type="submit">Play</button>
</form>
</div>
</body>
</html>
Stripping out all the extra bits in your code, here's how you'll need to handle the asynchronous loading on speechSynthesis.getVoices();
if (voiceLoaded()) {
speak();
} else {
speechSynthesis.addEventListener('voiceschanged', speak);
}
function speak() {
const utterance = new SpeechSynthesisUtterance('text');
utterance.voice = getFemaleVoice();
speechSynthesis.speak(utterance);
}
function getFemaleVoice() {
const voiceIndex = 4;
return speechSynthesis.getVoices()[voiceIndex];
}
function voiceLoaded() {
return speechSynthesis.getVoices().length;
}
If the voices array has loaded already then it'll speak the utterance, otherwise this code will add the event listener on the voiceschanged event which will fire once the browser loads the array of voices and then your callback to speak will run.

How to remove array objects from localStorage using dynamic buttons? [JS only]

New to JS here, been struggling with this one for a few hours now.
So I created a to do list with a button that stores objects in an array inside localStorage and also creates dynamic list items with content and delete buttons. Whenever I click the delete button it removes the dynamic list item but doesn't remove it from localStorage. I can't figure out how to assign each button to the specific array index in localStorage.
https://codepen.io/jupiterisland/pen/ooPXWV
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
var currentTask = newTaskList[i];
var taskIndex = newTaskList.indexOf(currentTask);
newElement();
function newElement() {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(){
var listItem = this.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
}
delNode.addEventListener("click", deleteTasks);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>My Task Board</h1>
<div class="container">
<form onsubmit="return submitFunc()">
<div>
<label for="">Task:</label>
<textarea name="name" rows="8" cols="80"placeholder="Please enter your task description"></textarea>
</div>
<div>
<label for="">Deadline:</label>
<input type="date" placeholder="Choose a date">
<input type="time" placeholder="Set time">
</div>
<div>
<label for="">Important:</label>
<input type="checkbox" name="" value="">
</div>
<button type="submit" name="button">Add Task</button>
<div id="error"></div>
</form>
</div>
<div>
<ul id="taskBoard"></ul>
</div>
</body>
</html>
var taskList = []; //build array
if(localStorage.taskList){ //call func to recreate li's on refresh
taskList = JSON.parse(localStorage.taskList) || [];
createTasks(taskList)
}
function fakeGuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function submitFunc() {
var task = { //build objects
desc: document.getElementsByTagName("textarea")[0].value,
date: document.getElementsByTagName("input")[0].value,
time: document.getElementsByTagName("input")[1].value,
important: document.getElementsByTagName("input")[1].checked,
id :fakeGuid()
};
if(task.desc && task.date !== ""){
taskList[taskList.length] = task; //put objects inside array
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
newTaskList = JSON.parse(localStorage.taskList); //retrieve array with parse
createTasks(newTaskList)
document.getElementById("error").style.display = "none";
return false; //prevent submit
} else {
document.getElementById("error").style.display = "block";
document.getElementById("error").innerHTML = "Please enter a task description and a date.";
return false;
}
}
function createTasks (newTaskList){
for (i = 0; i < newTaskList.length; i++) { // display objects in list items
newElement(i);
function newElement(currentIndex) {
var liNode = document.createElement("li");
var titleNode = document.createElement("h3");
var dNode = document.createElement("p");
var tNode = document.createElement("p");
var delNode = document.createElement("button")
liNode.className = "liNode";
titleNode.className = "titleNode";
dNode.className = "dNode";
tNode.className = "tNode";
delNode.className = "delete";
delNode.innerText = "Delete";
var titleText = newTaskList[i].desc;
var dateText = newTaskList[i].date;
var timeText = newTaskList[i].time;
var descNode = document.createTextNode(titleText);
var dateNode = document.createTextNode(dateText);
var timeNode = document.createTextNode(timeText);
titleNode.appendChild(descNode);
dNode.appendChild(dateNode);
tNode.appendChild(timeNode);
liNode.appendChild(titleNode);
liNode.appendChild(dNode);
liNode.appendChild(tNode);
liNode.appendChild(delNode);
document.getElementById("taskBoard").appendChild(liNode);
if (taskBoard.childElementCount > newTaskList.length) { //remove excess divs
for (n = 0; taskBoard.childElementCount - 2; n++) {
taskBoard.removeChild(taskBoard.firstChild);
}
}
function deleteTasks(node, currentTask) {
var listItem = node.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
taskList = taskList.filter(function(t) {
return t.id !== currentTask.id;
});
localStorage.taskList = JSON.stringify(taskList); //store array with stringify
}
var currentTask = newTaskList[currentIndex];
delNode.addEventListener("click", () => deleteTasks(delNode, currentTask));
}
}
}
Don't try to use index to manipulate DOM element. Instead use some kind of unique ID. In this case I created a fake GUID.
Read more on closure. The reason you are not able to pass index down to the function is because the index is bound to another context.
Any reason to stringify JSON for local storage? You can simply store an array.

Javascript SetInterval and get value Math.random

I have just created random number. My problems is how to get value random in id and how to set price changes automatically every 5 seconds and the fluctuation amplitude less than +/- 5% compared to the current, I don't know use the setinterval function everybody help me
My code Random Price :
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
It took me a while to work around the recursion issues I was running into, before I came up with a better solution.
//<![CDATA[
// external.js
function RandNumMaker(min, max, withinPercent, secondsInterval, decimalPlaces){
this.withinPercent = withinPercent || 5;
this.secondsInterval = secondsInterval || 5;
this.decimalPlaces;
if(decimalPlaces){
this.decimalPlaces = decimalPlaces;
}
var t = this, ia = [];
function rb(mn, mx){
return mx-Math.random()*(mx-mn);
}
var pn = rb(min, max);
function rn(){
var p = 1;
if(Math.floor(Math.random()*2) === 1)p = -1
return p*(Math.floor(Math.random()*t.withinPercent)+1)/100*pn;
}
function rf(){
var r, d = t.decimalPlaces;
pn += rn();
if(pn < min || pn > max){
return rf();
}
r = pn;
if(d)r = (Math.floor(Math.round(Math.pow(10, d+1)*r)/10)/Math.pow(10, d)).toFixed(d);
return r;
}
this.setDiv = function(div){
div.innerHTML = rf(); ia = [];
var iv = setInterval(function(){
div.innerHTML = rf();
}, this.secondsInterval*1000);
ia.push(iv);
return this;
}
this.stop = function(){
for(var i=0,l=ia.length; i<l; i++){
if(ia[i]){
clearInterval(ia[i]);
}
}
ia = [];
return this;
}
}
var doc, bod, C, E, N, old = onload; // for use on other loads
onload = function(){
if(old)old();
doc = document; bod = doc.body;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
N = function(className, inElement){
var ii = inElement || doc;
var cN = ii.getElementsByClassName(className);
if(cN){
return cN;
}
var tn = ii.getElementsByTagName('*');
for(var i=0,e,a=[],l=tn.length; i<l; i++){
e = tn[i];
if(e.className && e.className === className)a.push(e);
}
return a;
}
var sr = new RandNumMaker(0, 99.99), sl = N('slow');
var fr = new RandNumMaker(0, 99.99), fs = N('fast');
sr.decimalPlaces = 2;
fr.secondsInterval = 0.1; fr.withinPercent = 5;
for(var i=0,l=sl.length; i<l; i++){
sr.setDiv(sl[i]);
}
for(var i=0,l=fs.length; i<l; i++){
fr.setDiv(fs[i]);
}
}
//]]>
/* extrnal.js */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>test</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<hr />
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
</div>
</body>
</html>
Should work now!
After you create a new RandNumMaker(min, max) then you can set randomNumMarkerInstance.decimalPlaces, randomNumMakerInstance.withinPercent and randomNumMakerInstance.secondsInterval using simple assignment. randomNumMakerInstance.setDiv(div) starts it. randomNumMakerInstance.stop() stops it.
I think you can understand this code.
I tried to keep your code.
The key is to use setInterval function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script>
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function assignData(){
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
setInterval(assignData, 5000); //every 5 seconds
}
</script>
<body onload="assignData()">
<h2 id="price1"></h2>
<h2 id="price2"></h2>
<h2 id="price3"></h2>
<h2 id="price4"></h2>
<h2 id="price5"></h2>
<h2 id="price6"></h2>
<h2 id="price7"></h2>
</body>
</html>
My interpretation of your question: all elements to start with a random value between 0 and 99.99, and then every five seconds one randomly selected element is to be updated, changing its value by a random amount within 5% of its current value. (If you want to update every element every five seconds then change the random selection to be a loop instead.)
For simplicity in the demo snippet (click "Run code snippet" to see it work), I've used a group of <li> elements which I select with .querySelectorAll("li"), but if you really want to do it using element IDs you could say .querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7").
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
}
// get list of elements:
var elements = document.querySelectorAll("li");
// populate all elements initially:
[].forEach.call(elements, function(el) {
el.innerHTML = generateRandomNumber(0,99.99);
});
// update an element at random every second:
setInterval(function update() {
var element = elements[Math.floor(Math.random() * elements.length)];
var currentVal = +element.innerHTML;
element.innerHTML = generateRandomNumber(currentVal * 0.95, currentVal * 1.05);
}, 1000);
<ul>
<li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>
Note that five second intervals seemed too slow for a demo, so I've used one second (1000ms) here.
Further reading:
.querySelectorAll()
Array .forEach() method
Function.prorotype.call()
Math.floor()
unary plus operator
Hope this will help.
<body>
<p id="price1"></p>
<p id="price2"></p>
<p id="price3"></p>
<p id="price4"></p>
<p id="price5"></p>
<p id="price6"></p>
<p id="price7"></p>
</body>
<script>
//set initial random number for the elements
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
//set random number to elements with fluctuation +/- 5%
setRandomToElements()
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function setRandomToElements(){
//get current prices
var currentPrice1 = parseInt(document.getElementById('price1').innerHTML);
var currentPrice2 = parseInt(document.getElementById('price2').innerHTML);
var currentPrice3 = parseInt(document.getElementById('price3').innerHTML);
var currentPrice4 = parseInt(document.getElementById('price4').innerHTML);
var currentPrice5 = parseInt(document.getElementById('price5').innerHTML);
var currentPrice6 = parseInt(document.getElementById('price6').innerHTML);
var currentPrice7 = parseInt(document.getElementById('price7').innerHTML);
var fluctuation = 0.05;//5%
//random new numbers +/-5% current price
document.getElementById('price1').innerHTML = generateRandomNumber(currentPrice1-(currentPrice1*fluctuation), currentPrice1+(currentPrice1*fluctuation));
document.getElementById('price2').innerHTML = generateRandomNumber(currentPrice2-(currentPrice2*fluctuation), currentPrice2+(currentPrice2*fluctuation));
document.getElementById('price3').innerHTML = generateRandomNumber(currentPrice3-(currentPrice3*fluctuation), currentPrice3+(currentPrice3*fluctuation));
document.getElementById('price4').innerHTML = generateRandomNumber(currentPrice4-(currentPrice4*fluctuation), currentPrice4+(currentPrice4*fluctuation));
document.getElementById('price5').innerHTML = generateRandomNumber(currentPrice5-(currentPrice5*fluctuation), currentPrice5+(currentPrice5*fluctuation));
document.getElementById('price6').innerHTML = generateRandomNumber(currentPrice6-(currentPrice6*fluctuation), currentPrice6+(currentPrice6*fluctuation));
document.getElementById('price7').innerHTML = generateRandomNumber(currentPrice7-(currentPrice7*fluctuation), currentPrice7+(currentPrice7*fluctuation));
setInterval(setRandomToElements, 5000);
}
</script>
Fiddle

Websockets draggable instead of onclick

I'm making a simple to-do list with WebSockets. The simple-todo is created but I only managed to create it with a click instead of the draggable option it should have. I changed the click to draggable but it didn't work. here is the code I used.
<!doctype html>
<html>
<head>
<title>Simple Todo</title>
</head>
<body>
TODO <input type="text" id="newTodoItem">
<ul id="itemsTodo">
</ul>
PROGRESS
<ul id="itemsProgress">
</ul>
DONE
<ul id="itemsDone">
</ul>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
/* statusses
0: todo
1: progress
2: done
*/
window.addEventListener('DOMContentLoaded', function () {
socket.emit("submitNewTodoItemMessage", {});
}, false);
// Checks if a new toto item is submitted
document.onkeyup = function (e) {
if (e.which === 13) {
var newTodoItem = {};
newTodoItem.id = parseFloat(new Date().getTime() + Math.random());
newTodoItem.status = 0;
newTodoItem.action = document.getElementById("newTodoItem").value;
if (newTodoItem !== '') {
socket.emit("submitNewTodoItemMessage", newTodoItem);
}
document.getElementById("newTodoItem").value = "";
}
};
socket.on("listOfAllTodoItemsMessage", function (listOfAllTodoItems) {
var itemsTodo = [], itemsProgress = [], itemsDone = [];
for (var i = 0; i < listOfAllTodoItems.length; i++) {
var item = listOfAllTodoItems[i];
var dragItem = "<li>" + item.action + " <span class='changeStatus' id='p_" + item.id + "'>^</span> <span class='changeStatus' id='n_" + item.id + "'>v</span></li>";
if (listOfAllTodoItems[i].status === 0) {
itemsTodo.push(dragItem);
} else if (listOfAllTodoItems[i].status === 1) {
itemsProgress.push(dragItem);
} else if (listOfAllTodoItems[i].status === 2) {
itemsDone.push(dragItem);
}
document.getElementById('itemsTodo').innerHTML = itemsTodo.join("");
document.getElementById('itemsProgress').innerHTML = itemsProgress.join("");
document.getElementById('itemsDone').innerHTML = itemsDone.join("");
}
$(".changeStatus").draggable(function (e) {
socket.emit("submitStatusUpdateTodoItemMessage", e.target.id);
});
$(".changeStatus").css('cursor', 'pointer');
});
</script>
</body>
</html>
the code snippet is now on the draggable state but it isn't working. I'm using jquery so the draggable function should work I guess.

Why drop down display first character in capital after dot

I make a drop down on pop up screen. I am able to make that drop down using jQuery mobile. I used dform plugin. Everything is working fine. But I have one issue my first character display in capital letter when I added bootstrap.min.css - why?
When I run my program without bootstrap.min.css, it works fine. But when I run with bootstrap.css, it give first letter capital after . . As I written in small. This problem is only in chrome browser. When I run in firefox it works perfectly.
Can you please explain why it is occurring?
Here is my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link href=" https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
<link href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" rel="stylesheet" type="text/css" />
<link href=" https://dl.dropboxusercontent.com/s/hg36tk1m7rc4gnj/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script src="https://rawgit.com/daffl/jquery.dform/master/dist/jquery.dform-1.1.0.js"></script>
</head>
<body>
<button id="test">test</button>
<div data-role="popup" data-dismissible='false' data-transition="flip" id="tabbedPopup" data-theme="a"><a href="#"
data-rel="back"
data-role="button"
data-theme="a"
data-icon="delete"
data-iconpos="notext"
class="ui-btn-right cross-border cross-border closePopUp_h button circleClass" >Close</a>
<div id="commandInfo"></div>
<div id="commandInfoheader" class="comandinfoheader"></div>
<div data-role="collapsible-set" data-theme="b" data-content-theme="b" id="tabbedSet" data-iconpos="left">
</div>
</div>
</body>
<script type="text/javascript">
$(function () {
$('#test').click(function(){
createCommandPopUpTabs("tc_2-cmd_1_VoiceCallAudioMosMO");
$("#tabbedPopup").popup("open");
})
});
function createCommandPopUpTabs(id) {
var tabsHeader = ["InputParameter"];
var header = "<h3 >hh</h3>";
var commmand = "VoiceCallAudioMosMO";
var button = '<button onclick="return submitCommand("' + id
+ '")" style="" class="donebtn common-button1">Save</button>';
//$("#commandInfo").append(header);
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>hhh</h3></div>";
var content = generateCommandTabContent(tabsHeader[i], id);
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
$('input[name=direction]').parent().addClass('cleassr')
$("#tabbedSet").children(":first").collapsible( "expand" );
}
}
function generateCommandTabContent(name, id) {
var commandName = "VoiceCallAudioMosMO";
if (name == "InputParameter") {
var object = new window[commandName]();
var map = object.generateInputRequirment();
var formData = generateInputParamForm(map, id, status);
var form = $("<form />");
var dform = form.dform(formData);
return dform;
}
return null;
}
function VoiceCallAudioMosMO() {
COMMAND_NAME = "VoiceCallMos";
COMMAND_DISPLAY_NAME = "VoiceCallMOS";
this.map = {};
}
VoiceCallAudioMosMO.prototype.generateInputRequirment = function () {
if(typeof VoiceCallAudioMosMO.JSON!="undefined") {
var inputs = VoiceCallAudioMosMO.JSON.input;
for (var key in inputs) {
var inputField = inputs[key];
var inputParameterInfo = new InputParameterInfo();
for (var inputKey in inputField) {
inputParameterInfo[inputKey] = inputField[inputKey];
}
this.map[inputParameterInfo.name] = inputParameterInfo;
}
return this.map;
}
};
function InputParameterInfo() {
}
VoiceCallAudioMosMO.JSON = {
"commandName": "VoiceCallAudioMosMO",
"input": {
"refFileName": {
"displayDetail": "The reference file name to play in case of uplink channel",
"displayName": "Ref File Name",
"inputType": "SWITCH",
"name": "refFileName",
"inputValues": {
"USAReference.wav": "USAReference.wav",
"Reference.wav": "Reference.wav"
},
"value": "",
"unit": "NONE",
"required": false,
"visible": true
}
}
};
function generateInputParamForm(map, id, status) {
var formId = "form_" + id;
var formdata = {
elements : []
};
formdata.id = formId;
formdata.name = formId;
formdata.method = "post";
var div = {
html : []
};
div.type = "div";
div.class = "inputDiv";
div.caption = "<h3>Input Parameters</h3>";
var tabIndex = 1;
var arr = id.split("-");
var data = null;
for ( var key in map) {
var inputObj = map[key];
if (inputObj.visible==false && inputObj.required==false) {
continue;
}else {
var obj = createFormObject(inputObj);
}
//var obj = createFormObject(inputObj);
if(typeof data=="undefined"){
obj.value = inputObj["value"];
}else if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
}
/*if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
} else if (inputObj.hasOwnProperty("value")) {
obj.value = inputObj["value"];
}*/
if (status == "view") {
obj.readonly = "true";
obj.disabled = "disabled";
}
obj.tabindex = tabIndex;
var objName = "VoiceCallAudioMosMO";
obj.onblur = "validateElement('" + objName + "', '" + formId + "','"
+ obj.name + "')";
var unit = {};
var fieldset = {
html : []
};
fieldset.type = "fieldset";
fieldset.caption = inputObj["displayName"];
fieldset.html.push(obj);
$("div > fieldset legend:contains('*')").each(function () {
$(this).html($(this).html().replace("*", "<span class='red'>*</span>"));
});
div.html.push(fieldset);
tabIndex++;
}
formdata.elements.push(div);
return formdata;
}
function createFormObject(inputObj) {
var obj = {};
if (inputObj.hasOwnProperty("inputType")) {
if (inputObj["inputType"] == "LIST") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else if (inputObj["inputType"] == "NUMBER") {
obj.type = "text";
} else if (inputObj["inputType"] == "SWITCH") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else {
obj.type = "text";
}
} else {
obj.type = "text";
}
if (!inputObj.hasOwnProperty("displayName")) {
obj.type = "hidden";
}
obj.id = inputObj["name"];
obj.name = inputObj["name"];
obj.required = inputObj["required"];
obj.placeholder = inputObj["placeholder"];
obj.classes = inputObj["class"];
obj.className = inputObj["class"];
obj.class = inputObj["class"];
obj.title= inputObj["displayDetail"];
return obj;
}
</script>
</html>
It display a drop down when you click button.Drop down Value USAReference.wav.here I written "w" in small but it display in capital.but when I remove this css
https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
it show in small letter ? why ?
After a long research I found the solution own .there is a property
text-transform: capitalize written on 247 line Number bootstrap.css file.I remove that property.I am able to solve my problem

Categories