I am doing a Javascript exercise in which two images have to be superimposed, (an airplane flying over a beach). In it I must stop and start the animation and also be able to select the speed of the animation.
The first two functions (start and stop), work correctly, but not change the speed, are the following:
var playa = undefined;
window.onload = function () {
playa = document.getElementById("playa");
}
function parar() {
playa.style.animationPlayState = "paused";
playa.style.MozAnimationPlayState = "paused";
playa.style.WebkitAnimationPlayState = "paused";
}
function seguir() {
playa.style.animationPlayState = "running";
playa.style.MozAnimationPlayState = "running";
playa.style.WebkitAnimationPlayState = "running";
}
function velocidad(t) {
var valor = t + "s";
alert (valor);
console.log(valor);
playa.style.animationDuration = valor;
playa.style.MozAnimationDuration = valor;
playa.style.WebkitAnimationDuration = valor;
console.log(playa.style);
}
I change the speeds with the following select:
<select name="vel">
<option selected="selected" onclick="velocidad(4)">Normal</option>
<option onclick="velocidad(10)">Muy lento</option>
<option onclick="velocidad(8)">Lento</option>
<option onclick="velocidad(2)">Rápido</option>
<option onclick="velocidad(1)">Muy Rápido</option>
And the start and stop:
<input type="button" name="stop" value="stop" onclick="parar()" />
<input type="button" name="play" value="play" onclick="seguir()" />
The problem is when I press any selectable option, the value is not modified and changes are not applied.
You can call your method on change of select option:
<select name="vel" onchange="velocidad()">
<option selected="selected" value=4>Normal</option>
<option value=10>Muy lento</option>
<option value=8>Lento</option>
<option value=2>Rápido</option>
<option value=1>Muy Rápido</option>
</select>
In your method get the value of selected option and use that value.
javascript code for method velocidad:
function velocidad() {
var e = document.getElementById("vel");
var t = e.options[e.selectedIndex].value
var valor = t + "s";
alert(valor);
console.log(valor);
playa.style.animationDuration = valor;
playa.style.MozAnimationDuration = valor;
playa.style.WebkitAnimationDuration = valor;
console.log(playa.style);
}
Related
I am having an issue with an event listener on a select and a value not updating but cannot figure out what the issue.
Code is below. Basically need the price field to update based on the function above it. Unfortunately i cannot have them all in the same function and need to have them separate. The first console.log does show the value for y but the second does not show the value for price.
var factors = function factor(j) {
var mySelect = document.getElementById("mySelect").value;
if (mySelect == "car") {
lease = "166";
} else if (mySelect == "truck") {
lease = "200";
}
console.log("this is my lease value - " + lease);
return lease * j;
};
var monthlyprice = function monthlyprice() {
var price = factors(1);
console.log("this is my price -" + price);
};
var type = document.getElementById("mySelect");
type.addEventListener("click", factors);
<form action="">
<label for="mySelect">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
since monthlyprice calls factor() you want to place the listener on monthlyprice
var type = document.getElementById("mySelect");
type.addEventListener("change", monthlyprice);
function monthlyprice() {
var price = factor(1)
console.log("this is my price =" + price);
};
function factor(j) {
var y;
var z = document.getElementById("mySelect").value;
if (z == "car") {
y = "166";
} else if (z == "truck") {
y = "200";
}
console.log("this is my y value - " + y);
return y * j;
};
<form action="">
<label id="label">Shipment Type</label>
<select id="mySelect">
<option value="car">Car</option>
<option value="truck">Truck</option>
</select>
</form>
I have been trying lately to make a function that on change on the select box it return only the selected option value.
My markup looks like this:
<select id='rangeSelector'>
<option value='custom'>Custom</option>
<option value='7 days'>7 days</option>
<option value='14 days'>14 days</option>
<option value='WTD'>WTD</option>
<option value='MTD'>MTD</option>
<option value='QTD'>QTD</option>
<option value='YTD'>YTD</option>
</select>
and the javascript function:
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
var x = rangeSelector.children;
for (var i = 0; i < x.length; i++) {
var newX = x[i].value;
console.log(newX);
}
}, false);
What I am trying to do is when I click on 7 days to return only 7 days.
Don't read the <option>s. Read the <select>.
document.getElementById('rangeSelector').value
Other interesting bits include .selectedIndex and .selectedOptions.
(Of course, as Abhitalks notes in the comments, in your handler, the element getting will already done for you.)
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
console.log(rangeSelector.value);
}, true);
You do not need for loop for that, after firing event "change" rangeSelector.value already have value of chosen element.
so if you wanna add "active" to selected option you can do same:
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
var x = rangeSelector.children;
var y = rangeSelector.selectedIndex;
x[y].className = x[y].className + " active";
console.log(rangeSelector.value);
}, true);
but you should remove "active" class from all non-active, by looping them:)
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
var x = rangeSelector.children;
var y = rangeSelector.selectedIndex;
for (var i = 0; i < x.length; i++) {
x[i].className = ""; //or x[i].removeAttribute("class");`
}
x[y].className = x[y].className + " active";
console.log(rangeSelector.value);
}, true);
You could use jQuery for this, example:
$("#rangeSelector").on("change", function() {
var rangeSelect = document.getElementById("rangeSelector");
var value = selectJaar.options[rangeSelect.selectedIndex].value;
return value;
});
This first gets the dropdown, then get the selected value, and return it.
Try simply using this.value:
document.getElementById('rangeSelector').addEventListener('change', function(e) {
alert(this.value);
});
<select id='rangeSelector'>
<option value='custom'>Custom</option>
<option value='7 days'>7 days</option>
<option value='14 days'>14 days</option>
<option value='WTD'>WTD</option>
<option value='MTD'>MTD</option>
<option value='QTD'>QTD</option>
<option value='YTD'>YTD</option>
</select>
I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'
when i use split() the textfield value is empty, value for textfield from drop down that i need is e.g 15.
please show me where did i go wrong..
thanks,
here's the code :
<select name="cmbitems" id="cmbitems">
<option value="price1:15">blue</option>
<option value="price2:20">green</option>
<option value="price3:25">red</option>
</select>
<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">
var select = document.getElementById('cmbitems');
var pecah = select.split(":");
var hasil = pecah[1];
var input = document.getElementById('txtprice');
select.onchange = function() {
input.value = hasil.value;
}
Try this
<select name="cmbitems" id="cmbitems">
<option value="price1:15">blue</option>
<option value="price2:20">green</option>
<option value="price3:25">red</option>
</select>
<input type="text" name="txtprice" id="txtprice">
var input = document.getElementById('txtprice');
var select = document.getElementById('cmbitems');
select.onchange = function() {
var pecah = select.options;
var hasil = pecah[pecah.selectedIndex];
input.value = hasil.value.split(":")[1];
}
Try
var input = document.getElementById('txtprice');
document.getElementById('cmbitems').onchange = function() {
var select = document.getElementById('cmbitems').value;
var pecah = select.split(":");
var hasil = pecah[1];
alert(hasil);
input.value = hasil;
}
I'm trying to get it where a whole two paragraph div can be drawn onto a canvas. I'm mostly having problems with getting the div on a canvas without having to use all of the canvas tags and draw out every line. I think this is possible, let me know if it isn't. I'm intermediate with Javascript and Php, experienced with HTML, but new to canvas so try to keep it simple.
HTML Code:
<head>
<meta http-equiv="content-type" content="text/xml; charset=utf-8" />
<title>Quote It!</title>
<link rel = "stylesheet"
type = "text/css"
href = "passext.css" />
<script type = "text/javascript" src = "js2.js"></script>
</head>
<body>
<h1>It's as easy as One...Two...Three!</h1>
<div id = "instructions">
<p style = "text-align:center;">Instructions:</p>
<ol>
<li>Fill out quote and author fields, then press "Create Quote".</li>
<li>Adjust attributes and watch as it updates in real-time!</li>
<li>Click save and it will convert to a versatile image.</li>
</ol>
</div>
<div id = "tips_warnings">
<p style = "text-align:center;">Tips & Warnings:</p>
<ul>
<li>Don't forget to add quotation marks!</li>
<li>Don't forget a dash before the author.</li>
<li>To create a new quote, hit "Reset", and fill out the form.</li>
</ul>
</div>
<form name = "personalize" id = "personalize">
<fieldset class = "person">
<legend class = "legend">Personalize</legend>
<p>
<label class = "uinfo">Quote (One you make up or one you know):</label>
</p>
<p>
<textarea id = "quote"
rows = "10"
cols = "45"></textarea>
</p>
<p>
<label class = "uinfo">Author:</label>
<input type="text"
id = "write_author"
name = "author"
value = "eg. (-Billy Joe)"
onclick = "this.value = ''"/>
</p>
<p>
<label class = "uinfo">Text Color:</label>
<select id = "selColor" onchange="myFunction()">
<option value = "#ffffff">White</option>
<option value = "#000000">Black</option>
<option value = "#f09dee">Pink</option>
<option value = "#ff0000">Red</option>
<option value = "#1e4d0c">Green</option>
<option value = "#00ff00">Neon Green</option>
<option value = "#0000ff">Blue</option>
<option value = "#00ffff">Cyan</option>
<option value = "#ff00ff">Magenta</option>
<option value = "#ffff00">Yellow</option>
<option value = "#cccccc">Grey</option>
</select>
</p>
<p>
<label class = "uinfo">Text Style:</label>
<select id = "selStyle" onchange = "myFunction()">
<option value = "default">None</option>
<option value = "italic">Italics</option>
<option value = "underline">Underline</option>
<option value = "bold">Bold</option>
</select>
</p>
<p>
<label class = "uinfo">Background Color:</label>
<select id = "selBack" onchange = "myFunction()">
<option value = "null">None</option>
<option value = "#000000">Black</option>
<option value = "#ff0000">Red</option>
<option value = "#00ff00">Green</option>
<option value = "#0000ff">Blue</option>
<option value = "#00ffff">Cyan</option>
<option value = "#ff00ff">Magenta</option>
<option value = "#ffff00">Yellow</option>
<option value = "#ffffff">White</option>
<option value = "#cccccc">Grey</option>
</select>
</p>
<p>
<label class = "uinfo">Border:</label>
<select id = "selBorder" onchange="myFunction()">
<option value = "none">None</option>
<option value = "solid">Solid</option>
<option value = "double">Double</option>
<option value = "groove">Groove</option>
<option value = "ridge">Ridge</option>
<option value = "inset">Inset</option>
<option value = "outset">Outset</option>
<option value = "dashed">Dashed</option>
<option value = "dotted">Dotted</option>
</select>
</p>
<p>
<label class = "uinfo">Border Width:</label>
<select id = "selWidth" onchange = "myFunction()">
<option value = "500px">Large</option>
<option value = "375px">Medium</option>
<option value = "250px">Small</option>
</select>
</p>
<p>
<label class = "uinfo">Font:</label>
<select id = "selFont" onchange = "myFunction()">
<option value = "Times New Roman">Times New Roman</option>
<option value = "Serif">Serif</option>
<option value = "Sans-Serif">Sans Serif</option>
<option value = "Fantasy">Fantasy</option>
<option value = "Monospace">Monospace</option>
<option value = "Cursive">Cursive</option>
</select>
</p>
<p>
<label class = "uinfo">Font Size:</label>
<select id = "selSize" onchange = "myFunction()">
<option value = "105%">13pt</option>
<option value = "120%">14pt</option>
<option value = "130%">15pt</option>
<option value = "140%">16pt</option>
<option value = "150%">18pt</option>
</select>
</p>
<p class = "create_quote">
<input type = "button"
value = "Create Quote"
onclick = "myFunction()"/>
<script type = "text/javascript" src = "js2.js"></script>
<input type = "reset"/>
</p>
</fieldset>
</form>
<canvas id = "blank">
<p id = "blank1"></p>
<p id = "author"></p>
</canvas>
<input type = "button"
id = "save"
value = "Save"
onclick = "saveFuction()"/>
<script type = "text/javascript" src = "js2.js"></script>
</body>
</html>
Javascript Code:
function myFunction(){
var quote, quote1, fsize, fsize1, fColor, fcolor1, bcolor, bcolor1, font, font1, width, width1, border, border1, author, author1, author2, format, fstyle, fstyle1;
format = document.getElementById("blank");
var context = format.getContext("2d");
quote=document.getElementById("quote");
quote1=quote.value;
outPut = document.getElementById("blank1");
if (quote1 != "") {
outPut.innerHTML = quote1;
} else {
alert("You need to enter a quote!");
}
author = document.getElementById("write_author");
author1 = author.value;
author2 = document.getElementById("author")
if (author1 == "" || author1 == "eg. (-Billy Joe)") {
alert("Who wrote this?");
} else {
author2.innerHTML = author1;
}
fcolor = document.getElementById("selColor");
fcolor1 = fcolor.value;
format.style.color=(fcolor1);
fstyle = document.getElementById("selStyle");
fstyle1 = fstyle.value;
if (fstyle1 == "italic") {
format.style.fontStyle=("italic");
format.style.textDecoration=("");
format.style.fontWeight=("");
} else if (fstyle1 == "underline"){
format.style.textDecoration=("underline");
format.style.fontStyle=("");
format.style.fontWeight=("");
} else if (fstyle1 == "bold") {
format.style.fontWeight=("bold");
format.style.textDecoration=("");
format.style.fontStyle = ("");
} else if (fstyle1 == "default") {
format.style.fontWeight=("");
format.style.textDecoration=("");
format.style.fontStyle = ("");
}
bcolor = document.getElementById("selBack");
bcolor1 = bcolor.value;
format.style.backgroundColor=(bcolor1);
border = document.getElementById("selBorder");
border1 = border.value;
format.style.border=( border1);
if (border1 == "dashed") {
format.style.borderWidth=("3px");
} else {
format.style.borderWidth=("5px");
}
width = document.getElementById("selWidth");
width1 = width.value;
format.style.width=(width1);
if (width1 == "375px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "962.5px";
}else if (width1 == "250px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "1025px";
}else if (width1 == "500px") {
document.getElementById("blank").style.position = "absolute";
document.getElementById("blank").style.left = "900px";
}
font = document.getElementById("selFont");
font1 = font.value;
format.style.fontFamily=(font1);
fsize = document.getElementById("selSize");
fsize1 = fsize.value;
format.style.fontSize=(fsize1);
}
function saveFunction(){
format.location.href = format.toDataURL();
}
Any help would be appreciated.
You can't draw html elements directly on canvas.
You'll have to learn/use the canvas drawing commands.
However, some people have had success with this library that simulates html elements on canvas:
http://html2canvas.hertzen.com/
You might also want to know that canvas.toDataURL doesn't allow you to save the image data to a user's local file system for security reasons.
Alternatively,
There are many screen-grabbers out there. SnagIt is a good one: http://www.techsmith.com/snagit.html
Check out html2Canvas as markE said, it takes a dom element and converts it to a canvas, and then you can draw that canvas onto another canvas something like this:
http://html2canvas.hertzen.com/
var domElement = document.getElementById('myElementId');
html2canvas(domElement, {
onrendered: function (domElementCanvas) {
var canvas = document.createElement('canvas');
canvas.getContext('2d').drawImage(domElementCanvas, 0, 0, 100, 100);
// do something with canvas
}
}