Why does only the first div respond to function? - function

I'm creating an online quiz which will consist of three different answering alternatives in three divs called #useralt. All the divs will have the same id but different content. The div with the content that is the same as the #answer-div will trigger a "Correct!" div, while the others will trigger a "Sorry"-div.
I can only get the first #useralt-div to work, the following to get numb... Can anyone help me making all three of them work?
This is the site: http://www.juliawallin.se/moviecharades/play.html
$(document).ready(function(){
$("#useralt").click(function(){
var correctAnswer = $('#answer').text().toLowerCase();
var givenAnswer = $('#useralt').text().toLowerCase();
var match = correctAnswer.match(new RegExp("^#moviecharades (.+)$"));
correctAnswer = match[1];
if (givenAnswer == correctAnswer)
{
$("#correct").show("fast").delay("1000").hide("500"); //Slide Down Effect
$('#output').html(function(i, val) { return val*1+1 });
var el = document.createElement('div');
el.innerHTML = $("#output")[0].innerHTML;
document.getElementById('highscore').appendChild(el);
var interval = 1000 * 60 * 1;
APP.refresh(1, interval);
}
else
{
$("#correct").hide("fast"); //Slide Up Effect
$("#incorrect").show("500").delay("1000").hide("500");
}
});
});

ID must be unique, you need to use class. Change your id "useralt" to class then use:
$(".useralt").click(function(){
var correctAnswer = $('#answer').text().toLowerCase();
var givenAnswer = $(this).text().toLowerCase();
....
...

IDs must be unique. So that's not going to work. Try something like:
<div class="useralt" id="useralt1">
<div class="useralt" id="useralt2">
<div class="useralt" id="useralt3">

From w3 schools, http://www.w3schools.com/tags/att_global_id.asp
Specifies a unique id for the element. Naming rules: Must contain at least one character Must not contain any space characters In HTML, all
values are case-insensitive

Related

Equal height layout of 3 module content, best method?

In looking at this image you can see in an ideal world each box would have the same height of content in each box. However in the real world we can't control how many characters the client uses for a heading. Wondering thoughts on how to deal with a situation like this? Is it ok to just let it be as is?
This will create an array of heights of an element by class, then find the tallest, and then make them all that height.
<script>
var headerHeights = [];
var mclength = document.getElementsByClassName("myClass").length;
for (i = 0; i < mclength; i++) {
headerHeights[i] = document.getElementsByClassName("myClass")[i].getBoundingClientRect().height;
}
var headerMaxHeight = Math.max(...headerHeights);
for (i = 0; i < mclength; i++) {
document.getElementsByClassName("myClass")[i].style.height = headerMaxHeight+"px";
}
</script>
You will likely want to make this a function which replaces "myClass" with a function parameter so that you can call it for each class you add. You will also want to add a listener for when a person resizes their window to rerun the function.

Adding two javascript functions(depending on input)

I have put together a calculator what calculates a price, depending on user input. It works fine with one input, but now I have to scale it a little with a second user input. But here's the catch: the user might not want to put anything to the field, so it will be empty. And that's the thing that brakes my code. I could duplicate the calculator function and return the values and add those two together in a third function, but it will not work when there's an empty value.
Just for the sake of it, some trivial HTML code:
//When I only calculate with this user input, its easy
<input type="text" id="rocktext"><br>
// But how to consider this and do the same exact calculations like with the
//first one and add those two result together?
<input type="text" id="rocktext2"><br>
The code in the end should look like:
Take first user input, calculate the price(like in code below)
IF(!!) there is a second user input, calculate the price and add it to
the first one
Am I being a moron to try it with JS or just a moron in the firstplace?
Hope to hear from You, guys!
J.
The initial JS code is as follows:
function priceCalc() {
var inputs = document.getElementById("rocktext").value;
var length = inputs.length;
var accept = 6;
var initPrice = 8;
if (inputs<=accept){
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = initPrice + " dollars";
//I can also return the the value calculated here like so:
//retVal = initPrice;
}
else {
var intLength = parseInt(length, 10);
var lengthGap = intLength - accept;
var totals = lengthGap * 0.8 + initPrice;
var prec = totals.toPrecision(3);
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = prec + " dollars";
// Here also the return clause can be possible with the calculation result like so:
//retVal = prec;
}
// And the final return as an alternative to the innerHTML :
// return retVal;
}
Making it scalable, you can add a class to all the inputs which may be in the function (something like calcInput), so you iterate all of them and if the value isn't empty (and if it's a valid number), you put it in the calculation.
Or you can just verify if the second input is empty, if so, calls functionOne, if not, calls functionTwo:
function twoDifferentWays() {
var valueOne = document.querySelector("#rocktext").value;
var valueTwo = document.querySelector("#rocktext2").value;
if (!!valueTwo && !isNaN(valueTwo)) {
callsFunctionOne(valueOne, valueTwo);
} else {
callsFunctionTwo(valueOne, valueTwo);
}
}

How do I select a part of an array? Or match parts of one array with parts of another?

I have some drag and drop function where there are 8 items (dragArray) that can be dropped onto 2 big 'landing zones' (matchArray). But since I don't want them lie on top of each other, I've made an array where they are given positions (posArray).
var dragArray:Array = [drag_1, drag_2, drag_3, drag_4, drag_5, drag_6, drag_7, drag_8];
var matchArray:Array = [drop_1, drop_1, drop_1, drop_1, drop_2, drop_2, drop_2, drop_2];
var posArray:Array = [{x:412,y:246},{x:530,y:218},{x:431,y:186},{x:470,y:152},{x:140,y:111},{x:108,y:162},{x:179,y:210},{x:113,y:254}];
When all 8 items are dropped, a check button appears and I want to check if they are dropped onto the correct big landing zone. I tried using the following:
if (posArray[i].x != dragArray[i].x || dragArray[i].y != posArray[i].y )
But then, not only the landing zone must match, but the positions must also match.
When I use
if (matchArray[i].x != dragArray[i].x || dragArray[i].y != matchArray[i].y )
it doesn't work, because the positions of the (dragArray) items don't match with the registration points of the (matchArray) landing zones.
Is there any way of checking if the first 4 (drag_1, drag_2, drag_3, drag_4) items match with ANY of the first 4 posArray positions and the last 4 (drag_5, drag_6, drag_7, drag_8) match with ANY of the last 4 posArray positions?
If the goal is to check each element of one set against all elements of another set then you'll need to have two loops, one "nested" within the other. The general form of this algorithm in AS3 looks like
var allMatched:Boolean = true;
for(var i:Number=0; i<array1.length; i++)
{
var matchFound:Boolean = false;
for(var j:Number=0; j<array2.length; j++)
{
if(array1[i]==array2[j])
{
matchFound=true;
break; //exit the inner loop we found a match
}
}
if(!matchFound)
{
allMatched=false;
break; //we found an element in one set not present in the other, we can stop searching
}
}
if(allMatched)
trace("Everything from array1 was found somewhere in array2"); //For an element a in the set A there exists an element b in set B such that a = b
Let me know if this helps

find common words of two webpages on the fly

I have a list of species here:
http://megasun.bch.umontreal.ca/ogmp/projects/other/compare.html
And a list of species here:
http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=3524
I would like to find all species that are mentioned on BOTH pages. How can I do this quickly? (I dont mind if words not referring to species are to be found. I want to do comparision of words in general:)
Thanks for suggestions.
On each page in a console, do:
var html = document.body.innerHTML;
results = [];
html.match(/>([^<]+?)</g) // grab all values like ">...<"
.map(function(match) { // look for a long words..words..words
return match.match(/\w.*\w/);
})
.filter(function(match) { // ignore empty matches
return match!==null
})
.forEach(function(match) {
var text = match[0];
if (!text.match(/[0-9]/) && // ignore matches with numbers
results.indexOf(text)==-1) // add to results if not duplicate
results.push(text);
});
JSON.stringify(results);
Then do:
var page1 = JSON.parse(' /*COPY-PASTE THE RESULT OF PAGE 1*/ ');
var page2 = JSON.parse(' /*COPY-PASTE THE RESULT OF PAGE 2*/ ');
page1.map(function(s){return page2.indexOf(s)!=-1});
This is necessary to circumvent browser restrictions.
Demo:
> JSON.stringify( page1.filter(function(s){return page2.indexOf(s)!=-1}) )
'["Beta vulgaris","Spinacia oleracea"]'

xul-Get selection html

I have the following function that is supposed to get HTMLs for the user selected area on the web page. This function does not seems to work properly.
Sometime, it gets htmls which is not selected also.
Can anyone please look into this function? -- Thanks a lot.
//----------------------------Get Selected HTML------------------------
function getSelectionHTML(){
if (window.getSelection)
{
var focusedWindow = document.commandDispatcher.focusedWindow;
var sel = focusedWindow.getSelection();
var html = "";
var r = sel.getRangeAt(0);
var parent_element = r.commonAncestorContainer;
var prev_html = parent_element.innerHTML;
if(prev_html != undefined)
{
return prev_html;
}
return sel;
}
return null;
}
It looks to me like you're getting the contents of the parent element rather than the selection itself. If the parent element contains anything other than what you have selected, then you'll get that too.
var sel = focusedWindow.getSelection();
This line returns a selection object. It contains the exact text selected by the user. You then get the range from the selection and get the commonAncestorContainer. So if you have code like this:
<div id="ancestor">
<p>First sentence.</p>
<p>Another sentence.</p>
</div>
And your user selects from the 's' of the first sentence to the 's' of the second sentence then the commonAncestorContainer is the div element so you'll also get the rest of the text.
A good reason for this would be if you wanted to guarantee yourself a valid HTML fragment (this seems to be the case, implied by your function name), but if you just want the selected text then call the toString method on the range directly:
var focusedWindow = document.commandDispatcher.focusedWindow;
var sel = focusedWindow.getSelection();
var r = sel.getRangeAt(0);
return r.toString();