My javascript code is:
$("#yes").click(function() { mergeSort(arr); });
function mergeSort(arr)
{
var arr = getDataFromInput();
if (arr.length < 2)
return arr;
var middle = parseInt(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
writeResultToOutput(result);
}
function getDataFromInput() {
return $("#w").val();
}
function writeResultToOutput(resultHTML) {
$("#z").html(resultHTML);
}
My html is:
<body>
<label for="w">entry information</label><br>
<textarea rows="40" cols="100" name="w" id="w"></textarea>
Results
<div id="z"></div>
<button id="yes">Begin!</button>
</body>
Theoretically aim is to sort this in alphabetical order using mergesort however when i type some words like 'air field bored' and press begin nothing really happens. What is wrong with that code?
Error i have received:
ReferenceError: $ is not defined
I am aware html is not properly linked to JavaScript but this is not a problem as obviously i know how to connect those two.
I will give you the full code after modifications is (error is gone but still does not sort words):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$("#yes").click(function() { mergeSort(arr); });
function mergeSort(arr)
{
var arr = getDataFromInput();
if (arr.length < 2)
return arr;
var middle = parseInt(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
writeResultToOutput(result);
}
function getDataFromInput() {
return $("#w").val();
}
function writeResultToOutput(resultHTML) {
$("#z").html(resultHTML);
}
</script>
</head>
<body>
<label for="w">entry information</label><br>
<textarea rows="40" cols="100" name="w" id="w"></textarea>
Results
<div id="z"></div>
<button id="yes">Begin!</button>
</body>
</html>
What i want to use as arr is the input from the browser's level, I mean:
Latest version:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<label for="w">entry information</label><br>
<textarea rows="40" cols="100" name="w" id="w"></textarea>
Results
<div id="z"></div>
<button id="yes">Begin!</button>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$("#yes").click(function() {
var arr = getDataFromInput();
mergeSort(arr);
});
function mergeSort(arr)
{
if (arr.length < 2)
return arr;
var middle = parseInt(arr.length / 2);
var left = arr.slice(0, middle);
var right = arr.slice(middle, arr.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right)
{
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
writeResultToOutput(result);
}
function getDataFromInput() {
return $("#w").val();
}
function writeResultToOutput(resultHTML) {
$("#z").html(resultHTML);
}
</script>
</body>
</html>
Still no valid output, i mean no output whatsoever
For starters:
Your script is before your html. It starts running before it's rendered.
If you are going to leave it inside the HTML, put it before the body closing tag.
For executing a function on click, you can do it like this:
$("#yes").click(mergeSort());
No need to execute a anonymous function. You already have a named one.
And you are trying to pass a parameter that you haven't created before.
the "var arr" is inside a function.
Start checking these things and go from there. I'll be back here later.
Hope it helps you.
ReferenceError: $ is not defined means jQuery is not included or the code is written before including jQuery in your page
Include jQuery library and try again
http://code.jquery.com/jquery-1.10.2.min.js
EDIT
You need to call our function like this
$("#yes").click(function() {
var arr = getDataFromInput();
mergeSort(arr);
});
and remove var arr = getDataFromInput(); from mergeSort function
function mergeSort(arr)
{
//var arr = getDataFromInput(); this line is removed
if (arr.length < 2)
return arr;
Related
I am writing a small script to determine if an element is in the viewport...
The problem that I am having is my variable RET is always coming back as UNDEFINED
myscript.js
function myScriptObj() {
this.isElementInView = function (element, fullyInView) {
var RET;
$(window).scroll(function () {
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height();
var elementTop = $(element).offset().top;
var elementBottom = elementTop + $(element).height();
if (fullyInView === true) {
RET = (pageTop < elementTop) && (pageBottom > elementBottom);
console.log(`myscript.js: RET >>> ${RET}`);
return RET;
} else {
RET = (elementTop <= pageBottom) && (elementBottom >= pageTop);
console.log(`myscript.js: RET >>> ${RET}`);
return RET;
}
});
console.log(`myscript.js: RET >>> ${RET}`);
}
}
In example index.html looks like
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
...
<div class="row center" id="banner">
<img src="img/banner.jpg" width="514px" height="65px" border="0" />
</div>
...
<script src="js/myscript.js"></script>
<script type="text/javascript">
var myObj = new myScriptObj();
var _isInView = myObj.isElementInView(document.getElementById("banner"), false);
console.log(`index.html: myObj.RET >>> ${myObj.RET}`);
if (_isInView) {
console.log(`index.html: in view >>> ${_isInView}`);
} else {
console.log(`index.html: out of view >>> ${_isInView}`);
}
</script>
</body>
</html>
Again, myObj.RET is undefined, however, inside the function isElementInView the variable RET does get a value of true or false
can someone tell me what I am missing
Code edited. Apologizes for the incomplete first code
I've this code that takes input from the user, and it appends an image that matches that input. What I want to do is to set different buttons (200 aprox.) to append a different image if other button is pressed. The approaching I'm doing for this is to target the first if, within the first switch case, with the ("#id").length condition.
This is a short example of my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<section id="section">
<input id="input">
<button id="1"></button>
<button id="2"></button>
</section>
<div id="div"></div>
</body>
</html>
Javascript:
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(); });
});
var input = ['a','b','c'];
function test() {
var interval = setInterval(match, 1);
$("div").html("");
str = $("input").val().toLowerCase();
var i = 0;
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>",
"<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if ($("#1").length){
$("div").append(imgs[0]);
i++;
break;
}else if ($("#2").length){
$("div").append(imgs[1]);
i++;
break;
}
}
else {
clearInterval(interval);
$("input").val("");
}
}
}
Now, I've managed to make the if work, it shows the image, but if I press the second button, the else-if never works. What am I doing wrong?
Well I can't for the life of me figure out what you're trying to do with this code, but here is a working version of it...
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(this); });
});
var input = ['a','b','c'];
function test(caller) {
var interval = setInterval(match, 1);
var i = 0;
$("div").html("");
str = $("input").val().toLowerCase();
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>","<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/100px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg' alt='2'/>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Corythucha_ciliata.jpg/120px-Corythucha_ciliata.jpg' alt='3'/>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if (caller.id == "1") {
$("div").append(imgs[0]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[1]);
i++;
break;
}
case input[1]:
if (caller.id == "1") {
$("div").append(imgs[2]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[3]);
i++;
break;
}
}
} else {
clearInterval(interval);
$("input").val("");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>
<button id="1">1</button>
<button id="2">2</button>
<div></div>
I´m creating a game and I've got stuck with a counter in a function.
I want the function to loop five times and then if my element "nocolnum" has a value of 5, i need the function to exit or break.
here is my html:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<span id="opt1"></span>
<span id="nocolnum">0</span>
</body>
</html>
here is my js:
function func(num) {
num = num + 1;
var opt = document.getElementById('opt1');
opt.innerHTML= num + "%" ;
var move = setTimeout("func("+num+")",15);
var nocolnum = document.getElementById('nocolnum');
if(num == 100){
nocolnum.innerHTML++;
clearTimeout(move);
}
if (nocolnum == 5) {
// I dont know what to put here
// to break out
// a break, return or something??
}
var one = 0;
func(one);
}
if (nocolnum == 5) {
// I dont know what to put here
// to break out
// a break, return or something??
return false;
}
If you want to break function you can simlpy return
if (nocolnum == 5) {
return true;
}
or
if (nocolnum == 5) {
return false;
}
I have a javascript text typer code:
CSS:
body
{
background-color:black;
}
#writer
{
font-family:Courier;
font-size:12px;
color:#24FF00;
background-color:black;
}
Javascript:
var text = "Help Please, i want help.";
var counter = 0;
var speed = 25;
function type()
{
lastText = document.getElementById("writer").innerHTML;
lastText+=text.charAt(counter);
counter++;
document.getElementById("writer").innerHTML = lastText;
}
setInterval(function(){type()},speed);
HTML:
<div id="writer"></div>
I want to know how can i use <br> tag (skipping a line or moving to another line). I tried many ways but failed, I want that if I Typed My name is Master M1nd. and then i want to go on the other line how would i go?
I've made a jQuery plugin, hope this will make things easier for you. Here is a live demo : http://jsfiddle.net/wared/V7Tv6/. As you can see, jQuery is loaded thanks to the first <script> tag. You can then do the same for the other <script> tags if you like, this is not necessary but considered as a good practice. Just put the code inside each tag into separate files, then set appropriate src attributes in the following order :
<script src=".../jquery.min.js"></script>
<script src=".../jquery.marquee.js"></script>
<script src=".../init.js"></script>
⚠ Only tested with Chrome ⚠
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery.fn.marquee = function ($) {
function findTextNodes(node) {
var result = [],
i = 0,
child;
while (child = node.childNodes[i++]) {
if (child.nodeType === 3) {
result.push(child);
} else {
result = result.concat(
findTextNodes(child)
);
}
}
return result;
}
function write(node, text, fn) {
var i = 0;
setTimeout(function () {
node.nodeValue += text[i++];
if (i < text.length) {
setTimeout(arguments.callee, 50);
} else {
fn();
}
}, 50);
}
return function (html) {
var fragment, textNodes, text;
fragment = $('<div>' + html + '</div>');
textNodes = findTextNodes(fragment[0]);
text = $.map(textNodes, function (node) {
var text = node.nodeValue;
node.nodeValue = '';
return text;
});
this.each(function () {
var clone = fragment.clone(),
textNodes = findTextNodes(clone[0]),
i = 0;
$(this).append(clone.contents());
(function next(node) {
if (node = textNodes[i]) {
write(node, text[i++], next);
}
})();
});
return this;
};
}(jQuery);
</script>
<script>
jQuery(function init($) {
var html = 'A <i>marquee</i> which handles <u><b>HTML</b></u>,<br/> only tested with Chrome. Replay';
$('p').marquee(html);
$('a').click(function (e) {
e.preventDefault();
$('p').empty();
$('a').off('click');
init($);
});
});
</script>
<p></p>
<p></p>
Instead of passing <br> char by char, you can put a \n and transform it to <br> when you modify the innerHTML.
For example (http://jsfiddle.net/qZ4u9/1/):
function escape(c) {
return (c === '\n') ? '<br>':c;
}
function writer(text, out) {
var current = 0;
return function () {
if (current < text.length) {
out.innerHTML += escape(text.charAt(current++));
}
return current < text.length;
};
}
var typeNext = writer('Hello\nWorld!', document.getElementById('writer'));
function type() {
if (typeNext()) setInterval(type, 500);
}
setInterval(type, 500);
Also probably you'll be interested in exploring requestAnimationFrame (http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/), for your typing animation :)
I'm trying to make a simple JavaScript program which prompts you to enter a sentence on page load. This sentence is then split up into an array separated by a space " ".
My issue currently is that it's not converting anything to uppercase or lowercase at all. I can't seem to understand why and some help would be appreciated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>for-loop replacement exercise</title>
<script language="JavaScript" type="text/JavaScript">
var wordString = prompt("Please enter a sentence: ", 0);
var processedString;
var cont = boolean(true);
// this function is called upon page startup
function startMeUp() {
do {
wordString;
if (wordString == "") {
cont = boolean(false);
}
} while(cont);
processString(wordString);
document.write(processedString);
}
// this function is attempting to iterate through a array of strings and anything that is 4 characters long it is put to lower case
// otherwise if the iteration is less than 4 its put to upper case
function processString(someInput) {
var wordArray = someInput.split(" ");
var lengArray = wordArray.length;
for (var i = 0; i < lengArray; i++) {
if (lengArray[i] == 4) {
wordArray[i].toLowerCase();
} else if (lengArray[i] < 4) {
wordArray[i].toUpperCase();
}
}
processedString = wordArray.toString();
}
</script>
</head>
<body onload="startMeUp();">
</body>
</html>
Try assigning the return value to the array index, rather than just calling the function and not storing it:
wordArray[i] = wordArray[i].toLowerCase();
First your not calling startMeUp() so I added that. next you could simplify the code by using a map().
var wordString = prompt("Please enter a sentence: ", '');
startMeUp();
function startMeUp() {
document.write(processString(wordString));
}
function processString(someInput) {
return someInput.split(" ").map(v => {
if (v.length == 4) return v.toLowerCase()
if (v.length < 4) return v.toUpperCase()
return v
}).join(' ')
}