random number, fade in the answer - javascript

I'm really new to JS and not a developer by any stretch of the imagination! I've got the code setup to generate a random number for me from an input box and dropdown list. Basically start at x, choose a maximum number form the DDL and calculate a random number in between. Code came from CSS Tricks and I've tweaked it to work for me and coded up the HTML page.
All works fine, but I'd like to animate the answer. At the moment it just appears, and it's less than elegant. I'd like something as simple as fading it in. But all the functions I try cause the calc to stop working and no number appears, let alone animated. Any chance of some guidance as to where in my string of code I need the animation to go?
function IsNumeric(n){
return !isNaN(n);
}
$(function(){
$("#getit").click(function() {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
if ((IsNumeric(numLow)) && (IsNumeric(numHigh)) && (parseFloat(numLow) <= parseFloat(numHigh)) && (numLow != '') && (numHigh != '')) {
$("#randomnumber").text(numRand);
} else {
$("#randomnumber").text("Erm...");
}
return false;
});
$("input[type=number]").each(function(){
$(this).data("first-click", true);
});
$("input[type=number]").focus(function(){
if ($(this).data("first-click")) {
$(this).val("");
$(this).data("first-click", false);
}
});
});

Error message from the JS Console:
SyntaxError: illegal character
$(#randomnumber).fade("slow");
--^
For selectors you have to use strings: $("#randomnumber").fade("slow");

Related

javascript value is not updating after onmousevent

I use 1 span tag at the moment.
<span onmouseover="numberOne()" onclick="imgNumber(); return false" onmouseout="noHoverOne()" class="img1 img" id="new-img"> </span>
The span has a "deafult" image, when the mouse goes on the span, another image will be shown, when the mouse leaves the span, the default image will be shown again.
now the javascript:
function numberOne() {
var random2 = Math.floor((Math.random() * 3) + 1);
var random3 = Math.floor((Math.random() * 3) + 1);
do {
var random = Math.floor((Math.random() * 3) + 1);
} while (random === numberOne.last);
numberOne.last = random;
Random numbers are made here. So every time you leave the span and go on the span, there will be a different image.
if (random == 2) {
document.getElementById('new-img').style = "background-image: url('http://web-stars.nl/molgeld.jpg');";
} else if ((random==random2)==random3) {
document.getElementById('new-img').style = "background-image: url('http://web-stars.nl/vrijstelling.jpg');";
} else {
document.getElementById('new-img').style = "background-image: url('http://web-stars.nl/haspel.jpg');";
}
These are the images that will be shown depending on the number
return random;
}
var value = numberOne();
function imgNumber() {
document.getElementById('demo').innerHTML = value;
}
imgNumber();
This is where I am stuck. Before I even have touched the span tag with my mouse, there is already a random number and when I go with the mouse on the span tag, it shows a different image but not a different number. I want to use this number somehow to create a new level for my game. The game is influenced by the chosen image.
So there is a lot going on and it's pretty messy. So please, I would love to hear any kind of constructive feedback.
[EDIT] I will keep the JSfiddle up to date, but there is an error in the preview, it won't display anything. It's still useful Jsfiddle
use a wrapper function where you can call both imgNumber and numberOne
function mouseHover() {
var value = numberOne()
imgNumber(value)
}
function imgNumber(value) {
document.getElementById('demo').innerHTML = value;
}
<span onmouseover="mouseHover()" onclick="imgNumber(); return false" onmouseout="noHoverOne()" class="img1 img" id="new-img"> </span>
Your code is a bit illogical. It seems you want to randomly assign an image to an element background and get a different element each time. So put the image URLs in an array and randomly grab one, ensuring it's different to the last. This means you can add or reduce the images you want to display just by modifying the images array.
Also put all your data in an object rather than using globals, it's just neater. And give your functions names that tell you what they do.
E.g.
var imageData = {
pix: ['http://web-stars.nl/molgeld.jpg',
'http://web-stars.nl/vrijstelling.jpg',
'http://web-stars.nl/haspel.jpg'
],
random: null
}
function changeImage(el) {
// limit do loop just in case data is bad
// Infinite loops are bad...
var len = imageData.pix.length;
var i = len;
do {
var random = Math.random() * len | 0;
} while (i-- && imageData.random == random)
imageData.random = random;
el.style.backgroundImage = imageData.pix[random];
console.log(random, imageData.pix[random]);
}
function updateImageRef() {
document.getElementById('imageRef').textContent = imageData.random;
}
<div id="imageDiv" onmouseover="changeImage(this)" onclick="updateImageRef()">Image div</div>
<div id="imageRef"><div>

Assigning string to div value from javascript function across pages

I have a web app that outputs the results of a function as a double. The function compares two text documents and returns the percentage indicating the percentage of similarity between the two documents. When the user clicks a Compare button, the function runs and takes the user from the compare.jsp page to the results.jsp page, and displays a loading-bar that is filled in like so:
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}"
data-stroke="">
</div>
This works fine, the fan bar gets the correct percentage. However, I am also trying to color the fan bar using the data-stroke value based on this percentage. I have a simple javascript function to do this, but can't figure out how to pass the value. I've tried running the function in the body tag of the results.jsp page using "onload", but this doesn't work. Here is my JavaScript function:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.getElementById("levenshtein-distance");
if (percent <= 40.00) {
elem.setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem.setAttribute("data-stroke", orange);
} else {
elem.setAttribute("data-stroke", red);
}
}
I've done quite a bit of searching and can't seem to find an example that helped me solve this. Any help is very much appreciated.
////Update:
Trinh, that worked to change the color, thanks! My problem now is that I do, in fact, have multiple 'levenshtein-distance' ids and I am looping through them. So currently everything is being set to the same color. I should have mentioned this initially, sorry. I am comparing multiple pairs of files and outputting the loading-bar for each pair. If you have some idea about how to resolve the looping issue, that would be great, but thanks for the original solution either way! I updated my javascript function as follows:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.querySelectorAll("[id^=levenshtein-distance]");
for (var i in elem) {
if (percent <= 40.00) {
elem[i].setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem[i].setAttribute("data-stroke", orange);
} else {
elem[i].setAttribute("data-stroke", red);
}
}
}
And the full bit of code with the html loop is, and I am now calling the barSetLD(percent) at the very bottom of the page as you suggested:
<c:forEach items="${studentResults}" var="result" varStatus="loop">
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}">
</div>
</c:forEach>
<script type="text/javascript">
barSetLD("${result.percentage}");
</script>
Put your code at the very bottom of the page where all DOM has been loaded. Or at least make sure <div id="levenshtein-distance"/> exist and fully loaded before calling this document.getElementById("levenshtein-distance");. Also double check if you have multiple levenshtein-distance id...

turning CSS on / off globally

My goal is to have a button (controlled by a javascript function) that would toggle the entire CSS on the website on and off. I thought this was a common practice and was surprised when I couldn't find a complete solution here or on the web.
Here is what I got.
$("#button").click(function() {
var css = (document.styleSheets[0].enabled = true);
if (css == true)
{
document.styleSheets[0].disabled = true;
css = (document.styleSheets[0].enabled = false);
}
else if (css == false)
{
document.styleSheets[0].disabled = false;
}
});
A simple Jquery function that targets the button by ID and performs an if test. I could've ommited the variable, but this way I am able to check the value easily in console.log. I am able to turn the CSS off, but not back on. The program doesn't even get to the else condition.
I am aware that the else if is not really appropriate, but with just else (and even just with another if condition) the function doesn't run at all.
Second option that I thought of, and which might be much easier is just dynamically changing the contents of the link href attribute, where the path to the css file is given.
But I am struggling to target the href element with Javascript.
This is a simple Boolean toggle so write it as a simple toggle
$("#button").click(function() {
var sheet = document.styleSheets[0];
sheet.disabled = !sheet.disabled;
});
As for why your code isn't working as is,
var css = (document.styleSheets[0].enabled = true);
// same as
var css;
document.styleSheets[0].enabled = true;
css = true;
which means
if (css == true)
// same as
if (true == true)
which always holds so you'll always follow this code path
Well, for one you need to loop through all of the stylesheets.
Also, you can save some lines of code by using a counter, then on each button click increment the counter and use the % modulo operator to turn that into a 1 or a 0, which you can then coerce a boolean from using !!.
var count = 0;
var sheets = document.styleSheets;
$("#button").click(function() {
for(var i in Object.keys(sheets)) sheets[i].disabled = !!(++count % 2);
});
.demo {
background: #888;
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">Some Text</div>
<button id="button">Click It</button>
Your problem is that you are doing an assignment when you should be doing an equality check.
You have
var css = (document.styleSheets[0].enabled = true);
But you are really trying to do an equality check, i.e.,
var css = (document.styleSheets[0].enabled == true);
Notice the extra =. The single = does an assignment, so your current code is equivalent to this:
document.styleSheets[0].enabled = true
var css = document.styleSheets[0].enabled; // i.e., true
Because you set enabled to true, your if (css == true) condition is always satisfied, so your code always turns the CSS off and never turns it back on.
The fix, as Paul S. wrote in his answer, is just to toggle the value of document.styleSheets[0].disabled, as in:
$("#button").click(function() {
document.styleSheets[0].disabled = !document.styleSheets[0].disabled;
});
There's no need to set and track a new property enabled.
The issue seems to be that you are doing assignment, and not comparison, on this line:
var css = (document.styleSheets[0].enabled = true);
It should be
var css = (document.styleSheets[0].enabled == true);
Probably simpler, since you have a jquery tag on the question, to just do:
$stylesheets = $('link[rel="stylesheet"]');
$("#button").click(function() {
$stylesheets.attr('disabled', !$stylesheets.attr('disabled'));
});
If you want to modify every href in your DOM,
just use
$('a[href*=]').each(function () {
var $this = $(this);
$this.attr('href', $this.attr('href').replace();
});

Check if two radio buttons checked, then write. [HTML/JS]

I can't get my JS/HTML to write if x & y radio buttons is selected...
my code:
http://dumptext.com/6rR25ynt
There are a few things wrong with your code:
you define the function Pris(), but you miss the closing bracket, so the function is not available. Also the if that is testing whether the radio buttons are checked is not correct.
Test this:
<script type="text/javascript">
function Pris() {
var S4A = document.getElementById("S4A");
var S5A = document.getElementById("S5A");
var Skade1 = document.getElementById("Skade1");
var Skade2 = document.getElementById("Skade2");
var Skade3 = document.getElementById("Skade3");
var Skade4 = document.getElementById("Skade4");
if (S4A.checked && Skade1.checked){
document.write("2412kr")
}
}
</script>
There are a couple of things going on here. First, in your comparison, I think you're trying to see if both are checked:
if (S4A && Skade1 == checked){
But to do that would look like this:
if (S4A.checked && Skadel1.checked){
Second, you have an if block at the bottom which refers to variables which have not been defined:
if((x == false) && (y == false)){
}
Also as a general note, you want to use === instead of == as much as possible, because == does automatic type coercion.
Finally, and this is actually the first error I found, you have no closing brace for your Pris function. It looks like the if((x...etc block wasn't given a closing } of its own. Mismatched braces will keep your code from executing.
Hope this helps.
Edited to add: working jsbin

transfer data from textbox to textarea with javascript

I have a small problem with my javascript code, im trying make a small application with 2 textboxes and 1 textarea. When textbox 1 is filled in you can press enter and then the focus will go to textbox 2. When textbox 2 is filled then the data from textbox 2 will go automaticly to the textarea as somekind of storage. And i fould like it to work with only plain javascript so it could support all the browsers and older browsers like IE 8
I have a massive javascript and every function works but somehow the big picture doesnt work. Can someone help me figure out why my javascript isnt doing what i want. And what i want is explained above.
https://jsfiddle.net/LLfwhL3L/2/
I cleaned the fiddle up fith the jshint functions from jsfiddle and get no erros, but it still doesnt work
These are the functions where i think it goes wrong:
function AddToList() {
var bonregel = document.getElementById("bonregel");
var val = bonregel.value.toString();
if (val != "") {
var box = document.getElementById("bonregelbox");
if (box.value != "")
box.value += "\n";
box.value = box.value + val;
}
bonregel.value = "";
bonregel.focus();
}
var delayrec = [];
function delay(callback, id, calldelay) {
clearTimeout(delayrec[id]);
delayrec[id] = setTimeout(callback, calldelay);
}
function keyup(event) {
var locatiebox = document.getElementById("locatie");
var bonregelbox = document.getElementById("bonregelbox");
var bonregels = bonregelbox.value.split(/\r\n/).join(",");
var locatie = locatiebox.value;
if (event.keyCode == 125)
SubmitContent(locatie, bonregels);
else
delay(AddToList, "AddToList", 500);
}
The working fiddle
https://jsfiddle.net/LLfwhL3L/5/
This is the working fiddle and how it should work, but on my device with IE 8 it doesnt work. The text from textbox 2 isnt goeing into the textaera. How can i solve this?

Categories

Resources