Assigning string to div value from javascript function across pages - javascript

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...

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>

JavaScript append gone crazy

I am trying to build a simple 3 grid gallery, the images inside it are all with different heights and I was after a tiled gallery... So I have made one that works with a bit of JavaScript.
However, when I tried to add another gallery in the same page, something weird happened, live preview here: http://loai.directory/test/gallery
The HTML, CSS and JS can be found fully placed in this jsfiddle: http://jsfiddle.net/aY5Gu
As you can see in the live preview, all the gridElemetns in grid3 are appending to grid3 in all the threeGrid galleries! After trying to debug, I have concluded that the problem is from the JS:
//Three Grids System
var gridElement = $(".gridElement", ".grid3");
GalleryGrid(); $(window).resize(GalleryGrid);
function GalleryGrid() {
var grid3 = $('.threeGrids .grid3');
var width = $(window).width();
if (width < 1024 && width > 770) {
var grid1 = $('.threeGrids .grid1');
var grid2 = $('.threeGrids .grid2');
for (var i = 0; i < gridElement.length; i++) {
if (i < gridElement.length / 2) {
grid1.append(gridElement[i]);
} else {
grid2.append(gridElement[i]);
}
}
} else {
grid3.append(gridElement);
}
}
What is going wrong? I can't seem to be able to go figure out what is wrong from there.
That's because .threeGrids and .grid1... appear more than one time on your page. Therefore jquery automatically appends things to all of them.
Try selecting by something like:
$('.wrapper').each(
function(){
var grids = $(this).find('.threeGrids');
(...do manipulation with grids...)
}
);
This way you enter each .wrapper separately and deal with only elements that are inside it.

Trying to change the color of text on click in javascript

So I am trying to make something where whenever I click on the text it change's color.
Javascript:
function changecolor(){
var tc = document.getElementById("header").style.color.value;
if (tc = "#000000") { tc = "#0009FF"}
else if (tc == "#0009FF") { tc = "#FF0000"}
else if (tc == "#FF0000") { tc = "#15FF00"}
else if (tc == "#15FF00") { tc = "#FFA600"}
else {tc = "#000000"};
document.getElementById("header").style.color.value = tc;
}
html:
<div onclick="changecolor()"><h1 id="header" style="color:#000000;"> Nick's Basic Physic's Calculator </h1></div>
It is not working and I have not been able to figure out why. When I click on the text nothing happens.
Change
document.getElementById("header").style.color.value = tc;
to
document.getElementById("header").style.color = tc;
Working example:
http://jsfiddle.net/xEyLf/
your problem is in var tc = document.getElementById("header").style.color.value;
you have to change to tc = document.getElementById("header").style.color;in order to get the color into variable.
I have another solution... here's a jsfiddle: http://jsfiddle.net/9zfJA/
Keep in mind I'm using these jQuery methods (as well as the jQuery library itself), by simply switching between CSS classes:
hasClass(): to check if the class is present
addClass(): to add the correct class based on the condition above
removeClass(): remove all classes, I've basically built a "reset" function
I think there are errors in the way it functions and how you want it, but I've built it on the same logic you have in your question.

random number, fade in the answer

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

Simple image rotation with pure javascript, no jQuery

trying to come up with very simple image rotation using pure javascript without jQuery.
Something that I could call like that and it could place the image in same spot rotating it one by one.
rotator('<img src="image1.gif"/ >','<img src="image1.gif"/ >');
maybe someone could suggest a way of doing it? thank you.
UPDATE: By Rotation I meant, one disappears, another appears. Not angle rotation.
This sort of steps beyond the call of duty and probably isn't the best solution but nonetheless. A full Javascript function (handles by tag not by image)
<html>
<head>
<script>
/*rotate
desc: Rotate a set of first level child objects based on tag name
params:
id = Rotate elements container id
tag = Tag (nodeName - see textNode issue) of DOM objects to be cycled
*/
function rotate(id, tag)
{
/*Normalise string for later comparison*/
tag = tag.toLowerCase();
/*Get container DOM Object*/
var el = document.getElementById(id),
visibleIdentified = false;
hasBeenSet = false,
firstMatchingChild = false;;
/*Iterate over children*/
for(i = 0; i < el.childNodes.length; i++){
/*Set child to var for ease of access*/
var child = el.childNodes[i];
/*If element has the correct nodeName and is a top level chlid*/
if(child.parentNode == el && child.nodeName.toLowerCase() == tag){
/*Set first matching child in case the rotation is already on the last image*/
if(!firstMatchingChild)
firstMatchingChild = child;
/*If child is visible */
if(child.style.display == "block"){
/*Take note that the visible element has been identified*/
visibleIdentified = true;
/*Toggle its visibility (display attribute)*/
child.style.display = "none";
/*Once the visibile item has been identified*/
}else if(visibleIdentified){
/*If the next item to become visible has been set*/
if(hasBeenSet){
/*Toggle visibility (display attribute)*/
child.style.display = "none"
}
/*Catch the next item to become visible*/
else{
/*Toggle visibility (display attribute)*/
child.style.display = "block";
/*Take note that the next item has been made visible*/
hasBeenSet = true;
}
}
}
}
/*If the hasBeenSet is false then the first item is to be made visible
- Only do so if the firstMatchingChild was identified, more or less redundant
exception handling*/
if(!hasBeenSet && firstMatchingChild)
firstMatchingChild.style.display = "block";
}
/*Declare cycle*/
setInterval("rotate('test','div')",1000);
</script>
</head>
<body>
<!-- Example container -->
<div id="test">
<div style="display:block">fire</div>
<div style="display:none">water</div>
<div style="display:none">shoe</div>
<div style="display:none">bucket</div>
</div>
</body>
</html>
Your specific question I haven't seen before, but your basic premise has been asked many times. The reason why you can't find a call like
rotate('<img src="1" />', '<img src="2" />');
is because it is a bad idea according to programming practices. You are mixing content with script. Client-side web design relies on sandboxing certain features to speed development and make debugging easier. Content, Styling and Scripting are the major areas. Here you mix content (images) with scripting. You should really use one of the many existing image rotation scripts that rely on taking existing markup and rotating them.
<img src="a" />
<img src="b" />
<script>rotateImages();</script>
If you want to do it your way then you will need to parse your strings and then create element nodes based on them. Honestly I don't think its worth the time to code one up in that format unless this is for curiosity's sake.
I am going to answer my own question as I came up with solution by my own. Sorry if I did not explain well and I hope it could be useful to someone as well. I had to avoid jQuery for a special reason, sometimes its just has to be that way. Here is the code, feel free to comment and improve... a working version is here http://jsbin.com/oxujuf/3
function rotator(options) {
var a = options.delay;
var b = options.media;
var mediaArr = [];
for(var i = 0, j = b.length; i < j; i++) {
mediaArr.push(b[i].img);
}
document.write('<div id="rotatorContainer"></div>');
var container = document.getElementById('rotatorContainer');
var Start = 0;
rotatorCore();
function rotatorCore() {
Start = Start + 1;
if(Start >= mediaArr.length)
Start = 0;
container.innerHTML = mediaArr[Start];
setTimeout(rotatorCore, a);
}
}
And then later you may call it like that, with a simple API.
rotator({
delay : 3500,
media : [{
img : '<img src="http://lorempixel.com/output/abstract-h-c-149-300-7.jpg" width="149" height="300" border="0" />'
}, {
img : '<img src="http://lorempixel.com/output/abstract-h-c-149-300-2.jpg" width="149" height="300" />'
}]
});
This is covered on many older forums and blogs.
Here are a couple links:
http://www.go4expert.com/forums/showthread.php?t=1012
http://www.reachcustomersonline.com/2008/03/19/09.38.04/?doing_wp_cron=1326819656

Categories

Resources