Reddirecting to another page with created button - javascript

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.

Related

Id of an created element can't be used

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.

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);

updated values inside form do not transfer properly into new div

basically when you enter a value out of the specified range it gets updated to the minimum/maximum allowed, but the value of the var doesn't get updated to the max/min. (you can check by entering 1 into both forms and clicking on quote)
https://jsfiddle.net/epf4uyr6/
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
}
document.getElementById('cad').onkeyup = function() {
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}
your values not updating properly because , keyup function executing first and then onchange(cadCheck) function execute.
your current logic is inside onchange function , thats why value not updating properly.
move this line in onkeyup function , and remove it from onchange.
document.getElementById('cad').onkeyup = function() {
if (this.value >= 100) this.value = 99.99;
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}

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.

Trouble with onclick attribute for img when used in combination with setInterval

I am trying to make images that move around the screen that do something when they are clicked. I am using setInterval to call a function to move the images. Each image has the onclick attribute set. The problem is that the clicks are not registering.
If I take out the setInterval and just keep the images still, then the clicks do register.
My code is here (html, css, JavaScript): https://jsfiddle.net/contini/nLc404x7/4/
The JavaScript is copied here:
var smiley_screen_params = {
smiley_size : 100, // needs to agree with width/height from css file
num_smilies: 20
}
var smiley = {
top_position : 0,
left_position : 0,
jump_speed : 2,
h_direction : 1,
v_direction : 1,
intvl_speed : 10, // advance smiley every x milliseconds
id : "smiley"
}
function randomise_direction(s) {
var hd = parseInt(Math.random()*2);
var vd = parseInt(Math.random()*2);
if (hd === 0)
s.h_direction = -1;
if (vd === 0)
s.v_direction = -1;
}
function plotSmiley(sp /* sp = smiley params */) {
var existing_smiley = document.getElementById(sp.id);
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.setAttribute('onclick', "my_click_count()");
smiley_to_plot.style.position = 'absolute';
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
document.getElementById("smileybox").appendChild(smiley_to_plot);
}
function random_direction_change() {
var r = parseInt(Math.random()*200);
if (r===0)
return true;
else
return false;
}
function moveFace(sp_array /* sp_array = smiley params array */) {
var i;
var sp;
for (i=0; i < sp_array.length; ++i) {
// move ith element
sp = sp_array[i];
if (
(sp.h_direction > 0 && sp.left_position >= smiley_screen_params.width - smiley_screen_params.smiley_size) ||
(sp.h_direction < 0 && sp.left_position <= 0) ||
(random_direction_change())
) {
sp.h_direction = -sp.h_direction; // hit left/right, bounce off (or random direction change)
}
if (
(sp.v_direction > 0 && sp.top_position >= smiley_screen_params.height - smiley_screen_params.smiley_size) ||
(sp.v_direction < 0 && sp.top_position <= 0) ||
(random_direction_change())
) {
sp.v_direction = -sp.v_direction; // hit top/bottom, bounce off (or random direction change)
}
sp.top_position += sp.v_direction * sp.jump_speed;
sp.left_position += sp.h_direction * sp.jump_speed;
plotSmiley(sp);
}
}
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
function generateFaces() {
var smilies = new Array();
var s;
var i;
var css_smileybox=document.getElementById("smileybox");
var sb_style = getComputedStyle(css_smileybox, null);
// add info to the screen params
smiley_screen_params.width = parseInt(sb_style.width);
smiley_screen_params.height = parseInt(sb_style.height);
// create the smileys
for (i=0; i < smiley_screen_params.num_smilies; ++i) {
s = Object.create(smiley);
s.id = "smiley" + i;
s.top_position = parseInt(Math.random() * (smiley_screen_params.height - smiley_screen_params.smiley_size)),
s.left_position = parseInt(Math.random() * (smiley_screen_params.width - smiley_screen_params.smiley_size)),
randomise_direction(s);
smilies.push(s);
}
setInterval( function(){ moveFace(smilies) }, smiley.intvl_speed );
}
var click_count=0;
function my_click_count() {
++click_count;
document.getElementById("mg").innerHTML = "Number of clicks: " + click_count;
}
generateFaces();
The generateFaces() will generate parameters (for example, coordinates of where they are placed) for a bunch of smiley face images. The setInterval is within this function, and calls the moveFace function to make the smiley faces move at a fixed interval of time. moveFace computes the new coordinates of each smiley face image and then calls plotSmiley to plot each one on the screen in its new location (removing it from the old location). The plotSmiley sets the onclick attribute of each image to call a dummy function just to see if the clicks are registering.
Thanks in advance.
This is not a complete answer but it could give you some perspective to improve your code.
First of all, your idea of deleting the existing img so wrong. If it does exist, all you need is to just change its position so instead of this
if (existing_smiley !== null)
// delete existing smiley so we can move it
document.getElementById("smileybox").removeChild(existing_smiley);
you should do something like this:
if (existing_smiley !== null)
var smiley_to_plot = existing_smiley;
else {
var smiley_to_plot = document.createElement('img');
smiley_to_plot.setAttribute('src', "http://i.imgur.com/C0BiXJx.png");
smiley_to_plot.setAttribute('id', sp.id);
smiley_to_plot.style.position = 'absolute';
document.getElementById("smileybox").appendChild(smiley_to_plot);
smiley_to_plot.addEventListener('click', my_click_count);
}
smiley_to_plot.style.top = sp.top_position + "px";
smiley_to_plot.style.left = sp.left_position + "px";
As you can see new image is only being added if it's not already there. Also notice that adding events by using .setAttribute('onclick', "my_click_count()"); is not a good way to do. You should use .addEventListener('click', my_click_count); like I did.
Like I said this is not a complete answer but at least this way they response to the click events now.
FIDDLE UPDATE
Good luck!

Categories