Id of an created element can't be used - javascript

My problem is:
I created an element:
var crt = document.createElement("BUTTON");
var lst = document.createTextNode("\u2103");
crt.appendChild(lst);
crt.id = "change";
$(".information").append(crt); // information is a div
When it is clicked, temperature is changing from Celsius to Fahrenheit and back:
var find = true;
var c;
var d = document.getElementById("change");
$( "#change" ).click(function() {
if(find === true) {
c = Math.trunc(s * 1.8 + 32); // s is the temperature in celsius from start
t.innerHTML = "<br>Temperature: " + c;
d.innerHTML = '℉'
find = false;
} else {
c = Math.trunc((c - 32) / 1.8);
t.innerHTML = "<br>Temperature: " + c;
d.innerHTML = "℃";
find = true;
}
});
If i try to change something to id "change" on CSS, everything works fine.. But when i use it in script doesn't work.. But if the element with id "change" is created manually from the start on document, the code works.. Can you guys tell me what is the problem ? Why using it like this doesn't work ?
Thanks in advance.

The code on lines 49-67 in the supplied codepen execute and attempt to set a click handler on the element with the id of change. The element is not yet in the document when the code runs.
You will need to call that code after you dynamically create the element with the id of change.

Related

Javascript 'Dot Dot Dot' While Calculating

I have a function to display dot dot dot in a popup window while generating a report. I want to display the text:
Generating Report.
Generating Report..
Generating Report...
...repeat, until the report is ready. So far I've only been able to get the three dots in the popup without the other text. Here is my code snippet:
on(link, "click", function(){
var dots = window.setInterval( function() {
var wait = document.getElementById("reportLink");
if ( wait.innerHTML.length > 2)
wait.innerHTML = "";
else
wait.innerHTML += ".";
}, 400);
domAttr.set(dom.byId("reportLink"), "innerHTML", dots);
I tried this but it didn't work:
domAttr.set(dom.byId("reportLink"), "innerHTML", "Generating Report" + dots);
The function you're passing to setInterval is directly manipulating the dom element instead of returning a value (which wouldn't work anyway), so you "Generating Report" + dots won't work since dots is just a reference to the setInterval function. Instead, you need to modify your setInterval function using something like this (untested since I'm not sure what JS library/framework you're using):
var dots = window.setInterval( function() {
var wait = document.getElementById("reportLink"),
msg = "Generating Report",
msgLen = msg.length;
// Initialize to msg if blank
wait.innerHTML = (wait.innerHTML === "")
? msg
: wait.innerHTML;
if (wait.innerHTML.length >= (msgLen + 2))
wait.innerHTML = msg;
else
wait.innerHTML += ".";
}, 400);
Instead of initializing and testing your message by empty string, this uses the actual message you want to show. I also made the number of dots configurable by variable instead of using a "magic number".
[EDIT 1]
Make sure you remove this line (and any derivatives):
domAttr.set(dom.byId("reportLink"), "innerHTML", dots);
The function you're passing to setInterval is doing all the work.
[EDIT 2: Fixed the excessive dots on first run by initializing to msg if the reportLink element is empty.]
Try this:
var dots = window.setInterval( function() {
var wait = document.getElementById("reportLink");
if ( wait.innerHTML.length > 19)
wait.innerHTML = "";
else
wait.innerHTML += ".";
}, 400);
var text = "Generating Report" + dots;
domAttr.set(dom.byId("reportLink"), "innerHTML", text);
When you check the length you need to include the length of 'Generating report'.
maybe this?
var wait = document.getElementById("reportLink");
var loop = 0;
var text = "Generating Report";
window.setInterval( function() {
if ( loop > 2) {
wait.innerHTML = text;
loop = 0
} else {
wait.innerHTML += ".";
loop++
}
}, 400);

Reddirecting to another page with created button

I have this piece of code. If conditions are met i create a button "Show on Map". Now I need to run onclick event on created button that reddirects the user to a map on new URL. I tried with "window.location" in function go_to_map but it doesn't work. Any help?
function coordinates_Conv (d, m, s) {
return d + m / 60 + s / 3600;
}
function alarm(){
var lat_d = parseInt(document.getElementsByClassName("lat_deg")[0].value);
var lat_m = parseInt(document.getElementsByClassName("lat_min")[0].value);
var lat_s = parseInt(document.getElementsByClassName("lat_sec")[0].value);
var lon_d = parseInt(document.getElementsByClassName("lon_deg")[0].value);
var lon_m = parseInt(document.getElementsByClassName("lon_min")[0].value);
var lon_s = parseInt(document.getElementsByClassName("lon_sec")[0].value);
if ((coordinates_Conv (lat_d,lat_m,lat_s)<=90) && (coordinates_Conv (lat_d,lat_m,lat_s)>=0) && (coordinates_Conv (lon_d, lon_m, lon_s)<=180) && (coordinates_Conv (lon_d, lon_m, lon_s)>=0)){
document.getElementById("vypocet").innerHTML= String(Math.round(coordinates_Conv (lat_d,lat_m,lat_s)*1000)/1000) + "<br>" + String(Math.round(coordinates_Conv (lon_d, lon_m, lon_s)*1000)/1000);
var show_map = document.createElement("button","map");
show_map.setAttribute("id","map");
show_map.setAttribute("onclick", go_to_map);
show_map.innerHTML = "Show on map";
document.body.appendChild(show_map);
}
else {
alert("Invalid input");
}
}
function go_to_map(){
var targetMap = "https://www.mapurl.com/"
window.location=targetMap;
}
Your onclick handler never gets called in the first place.
To set it handler correctly, set the element's onclick directly:
show_map.onclick = go_to_map;
You need to replace show_map.setAttribute("onclick", go_to_map); with show_map.onclick = go_to_map;.
This is because onclick is an event and not an attribute.

Fading out in Javascript

Hey I'm new to javascript and I'm working on a small chat program right now.
I've got all the chatlogs (global& private and stuff..) but i want to add a button which can make (most of) the elements of these little 'clients' fade out and in, so that you dont have to see ALL of them at one time, just the ones you want.
The (relevant) code with the example element mess1:
h=0;
newroom = function (roomname) {
//create new container
var div = document.createElement('div');
div.className = 'container';
//new text input
var mess = document.createElement('input');
mess.type = 'text';
mess.id = 'mess1' + i;
div.appendChild(mess);
//minimizer button
var min = document.createElement('input');
min.type = 'button';
min.value = 'Minimize chat';
min.id = 'min' + i;
div.appendChild(min);
document.body.appendChild(div);
document.getElementById("min" + h).addEventListener("click", function (){
//this is where the magic happens
}
h++;
};
I've tried document.getElementById("mess1" + h).style.visibility = 'hidden';, but that just makes the element disappear, leaving a big ugly blank space behind.
I thought document.getElementById("mess1" + h).fadeOut('slow'); would fix that, but it just doesn't do anything...
Thanks in advance for your answers
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
first of all I will recommend to use jQuery, it will make your life much more easy. In jQuery, you can fade the element and then remove it like this
$("#mess1" + h).fadeOut('slow',function(){
$("#mess1" + h).remove();
});
It will first fade the element and will then remove it from node if required
You can use
document.getElementById("mess1" + h).style.display= 'none';
it will hide element without empty space. But if you whant to hide element with animation you can use eq. this jquery:
$("#mess1" + h).hide('slow')
or eq. 'fast' - as parameter

Record keypress and response time without advancing

I'm very new to JavaScript. I have a Qualtrics survey and I'm trying to create a question to which respondents must first press the spacebar, and then respond to a math problem on the screen. What I want is for Qualtrics to record (1) whether they press the spacebar (score as "C") or not (score as "X"), (2) if they do, how long it took them to press the spacebar from when the page appeared, and (3) to NOT advance to the next screen on the keypress, since they still have to answer the math problem on the screen. Here's what I've been trying:
Body of the Qualtrics question Q1:
Please press the spacebar, then solve this problem: 1+12+15-13-3+19-9=?
JavaScript associated with Qualtrics question Q1:
Qualtrics.SurveyEngine.addOnload(function()
{
var day = new Date();
trialstart = day.getTime();
$(document).on('keydown', function(e) {
if(e.keyCode === 32) {
var day = new Date();
trialend = day.getTime();
rt = trialend - trialstart;
document.getElementById("Q1").value = document.getElementById("Q1").value + "C" + rt + ",";
}
else{
document.getElementById("Q1").value = document.getElementById("Q1").value + "X" + ",";
}
});
});
Right now, this script isn't doing anything; Qualtrics outputs whatever is typed into the response textbox associated with Q1 (for responding to the math problem), but doesn't record whether they pressed the spacebar or their response time for pressing that key. Any help would be greatly appreciated. Thanks.
It is likely that you are seeing no output from this because you're using "Q1" as the ID. Qualtrics element ID's are actually a bit different from that, so the best way to find them is to preview your survey and inspect them using your browser to find the proper ID.
Now for a more full answer, your Javascript has no way to unbind the keypress event. So it will always end up as X, not C, unless they end their text entry with a space. Instead try something like this:
Qualtrics.SurveyEngine.addOnload(function(){
var pageStart = new Date();
var trialstart = pageStart.getTime();
var that = this;
that.hideNextButton();
var para = document.createElement("footnote");
var test = document.getElementById("Buttons");
var node = document.createElement('input');
var next = document.getElementById("NextButton");
var rt;
node.id = "newButton";
node.type = "button";
node.name = "newButton";
node.value = " Continue ";
var fired = 0;
var spaceFirst = '';
$(document).on('keydown', function(e) {
if(fired != 1){
if(e.keyCode === 32) {
var day = new Date();
var trialend = day.getTime();
rt = trialend - trialstart;
spaceFirst = 'C';
fired = 1;
}
else{
spaceFirst = 'X';
fired = 1;
}
}else{}
});
node.onclick = function stuff(){
if(spaceFirst == 'C'){
document.getElementById("QR~QID1").value = document.getElementById("QR~QID1").value + ', ' + spaceFirst + ", " + rt;
}else if(spaceFirst == 'X'){
document.getElementById("QR~QID1").value = document.getElementById("QR~QID1").value + ', ' + spaceFirst;
}else{}
window.alert(document.getElementById("QR~QID1").value);
that.clickNextButton();
};
para.appendChild(node);
test.insertBefore(para, next);
});
What this does is, hides the next button from view and creates a new button in it's place. (You will need to style this button, id = "newButton", to match your current button). Then it listens for the first keydown event, if it is a space, then it sets a variable equal to C, otherwise it sets it equal to X. Then it disables the keydown listener so that it doesn't fire after every keypress.
When the new button is pressed, it adds the appropriate X or C and the page time. You can remove or comment out the alert, as it is just for testing/debugging purposes.

Change background color with local.Storage (value)

I want to change the background-color of an div:
Arrow Box
For this i have to divs wich you can click. The triggerd function saves the local storage value of the "farbe" key.
<div class="radior" style="background-color:#8066CC;" onClick='localStorage.setItem("farbe","#8066CC");hey()'></div>
So after that, the value of the key "farbe" is asked. Besides this is makes an case ... I think you better read my code, because think i need some englisch lessons sorry!
function hey(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black"
case "#1bc38e":
var h = "turk"
case "#C3594B":
var h = "red"
case "#8066CC":
var h = "lila"
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=""+h+""; ;
}
SOmehow it doesnt function!
Or you watch an example of my problem at fiddle http://jsfiddle.net/PpsLH/4/ ! Greetings from Germany!
Change your function to:
hey = function(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black";
break ;
case "#1bc38e":
var h = "turk";
break ;
case "#C3594B":
var h = "red";
break ;
case "#8066CC":
var h = "lila";
break ;
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h;
}
By the way, lila is not a valid HTML color, so it will not work.
You should remove any inline event handlers from your code. Also the whole switch section and changing to named CSS colors seem redundant. Check out this bit of code written in jQuery
var box = $('div.arrow_box');
$('body').on('click','div.radior',function(e){
var color = $(e.target).css('backgroundColor');
localStorage.setItem('farbe',color);
box.css('backgroundColor',color);
});
and a working fiddle http://jsfiddle.net/chrisdanek/BaJvC/5/
try this
<div class="arrow_box"><a>Arrow Box</a></div>
<div class="radior" style="background-color:#C3594B;" onClick="localStorage.setItem('farbe','#C3594B');window.hey()"></div>
<br>
<div class="radior" style="background-color:#8066CC;" onclick='localStorage.setItem("farbe","#8066CC");window.hey()'></div>
and for javascript
window.hey = function ()
{
var h="";
if (localStorage.getItem("farbe")=="#121212")
{
var h = "black";
} else
if (localStorage.getItem("farbe")=="#1bc38e")
{
var h = "turk";
} else
if (localStorage.getItem("farbe")=="#C3594B")
{
var h = "red";
} else
if (localStorage.getItem("farbe")=="#8066CC")
{
var h = "lila";
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h+"";
}

Categories