How to detect in which line the cursor is? - javascript

I know, this might get pretty damn complicated, maybe almost impossible, but maybe someone of you knows the way:
Im currently writing an editor for a self-created, plainsimple language (5 keywords, WUHA!) which works pretty well already. But that's not the point here, now I want to create an editor for it with syntax highlighting. Yes, I want it online if possible, so my only chance is JavaScript/jQuery.
I dont have much code yet, this is all I got so far:
<!DOCTYPE html>
<html>
<head>
<title>Kevcode Editor</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(){
var keywords = ["KEYWORD2", "KEYWORD3", "KEYWORD4"];
$("#editor").keydown(function(e) {
if(e.keyCode == 13) {
//GET THE LINE HERE
//mark keywords here
}
});
});
</script>
</head>
<body style="background-color: grey;">
<label for="editor"><textarea id="editor" style="width: 1200px; height: 800px;"></textarea></label>
</body>
</html>
So my plan was to create a textarea and if I press Enter (which is represented by the keycode 13), ill run a script which checks every line and recolors the keywords. But then I thought that it would be a huge waste of resources to check the whole script. Of course the scripts wont be too long with 5 keywords, but if I add more and more, it would be horrible to check the whole code. So i thought that just checking the current line where I changed something would save me a lot of time. But how can I implement such a logic? How can I tell jQuery in which line the cursor currently is?
Sorry if I explained something unclear, if you got any questions please ask and I will give as much information as possible.
Oh, and don't give me finished solutions please. Ill do this for training purposes.

This is will help you to find cursor position in textarea.
javascript:
var cursorPosition = $('#myTextarea').prop("selectionStart");
Html:
<textarea id="myTextarea" rows="40" cols="50"></textarea>

try this:
<textarea onkeyup="getLineNumber(this, document.getElementById('lineNo'));" onmouseup="this.onkeyup();"></textarea>
<div id="lineNo"></div>
<script>
function getLineNumber(textarea, indicator) {
indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
}
</script>

Related

Having trouble with jmHighlight

I am very new to Javascript (ok, I've done 'Hello World' alright =]) and my other web programming skills are very limited.
I am trying to implement jmHighlight into one of my already created webpages but found I can't even get it to work in a clean page of its own. I've obviously made a very rudimentary mistake somewhere but can't figure out where so I'm hoping someone can help.
Here's what I've tried which doesn't work:
<!DOCTYPE html>
<html>
<head>
<style>
.context {
font-size:14px;
font-family:verdana;
}
span.highlight {
background-color:#000000;
font-color:#ffffff;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="jquery.jmHighlight.min.js"></script>
</head>
<body>
<p class="context">some text</p>
<input type="button" value="Try it" onclick="myFunc()">
<script>
function myFunc(){
jQuery(".context").jmHighlight("some");
alert("Done!");
}
</script>
</body>
</html>
The alert works so I think the basic code is ok, I think its more the syntax of the plugin I've gotten wrong. The author shows his work here: here on GitHub and altered his syntax in section 2 for a fixed keyword ('some') instead of using a text box for now. The include is in the same location as my page, but doesn't show in the debugger when I preview the page as loaded...
I have also tried lifting the code from his basic example Fiddle here but still can't get it to work. I've also had a look at other jmHighlight questions here on SO, but can't manipulate them to work for me.
If someone could kindly point me in the right direction, or supply me with a very simple but complete working example that I can dissect myself to figure out where I went wrong, I'd be very appreciative!
This code is working in Chrome, I have tried it and here is a fiddle which also shows it is working.
The only thing I think may not be right is your path to jmHighlight or the version of jmHighlight.
jmHighlight was also renamed to jquery.mark. Here is a rawgit URL pointing to the .min.js:
https://rawgit.com/julmot/jquery.mark/master/dist/jquery.mark.min.js

Javascript run() Function is Not Defined

I know there are a lot of questions like this, but none of them seemed to solve my problem. I have this piece of code that won't run because it says Uncaught ReferenceError: run is not defined. I have tried to move the function into the body of the HTML, but to no avail. My code:
<!DOCTYPE html>
<html>
<textarea name="Text1" cols="100"rows="20" id="textbox">
</textarea>
<button onclick="run()">Export to C++</button>
<script type="text/javascript">
function run() {
var code=new Array();
var input = document.getElementById("textbox").value;
//convert things that are not subroutines here
code.push(input);
code.push("}");
...
for (var i=0;i<code.length;i++)
{
document.write(code[i]+"<br>");
}
}
</script>
</html>
The ... is irrelevant code.
Why isn't this working? Any ideas on how to fix it?
Thanks
Seems it working fine for me, but as I can see the only reason for the problem is the following.
Your page is loading piece by piece from up to down, so all the scripts are going to be included and executed one by one, all the elements are going to be shown one by one as well.
That's not this case in fact, because you are using "on click" event and there are no init actions, so it should be working, but you can try to move your <script></script> at the top (before you assign event).
<!DOCTYPE html>
<html>
<textarea name="Text1" cols="100"rows="20" id="textbox">
</textarea>
<script type="text/javascript">
you script here
</script>
<button onclick="run()">Export to C++</button>
</html>
You may also replace the whole code inside of
<script></script>
by something like alert("Hello"); to check if it's working. Possible you have the issue with internal code.

How to get my jQuery before() call to work?

I have tried using JavaScript and jQuery with my HTML file, but it is not working properly. Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
body {white-space: nowrap;}
h1 {white-space: nowrap;}
</style>
<script src="jquery.js"type="text/javascript"></script>
<title>SolicitueCotizaciones</title>
</head>
<body>
<script>
function myFunction() {
$("input[type='button'][value='Agregar Pieza']").before("<p>new text</p>")};
</script>
<br/> Descripcion:
<br/>
<textarea id="improve" rows="3" cols="20"></textarea>
</p>
<div class="divider"/>
<div style="align-items:left"></div>
<p>
</p>
<p>
<input type="button" value="+Agregar Pieza" onclick="myFunction()">
</p>
</body>
</html>
I have also tried copying code from tutorial websites that work properly but when I run them in my computer, they stop working. Can anyone help me figure out what's happening and what I should do to solve it?
EDIT: What I'm trying to achieve is to add the new text above the "+agregar pieza" button and below the text input box labeled "descripcion" once you press the "+agregar pieza" button, but this never happens. I have tried the corrections that were posted in the comments, and I edited the code above to include them. However, as of this edit, it is still not working at all. I would like to use the .before command from jquery to achieve the desired result, but if there is a better way to do this, I would like to know.
First, jQuery is not native to your browser, you need to load it before using it. The tutorials should help you here.
Second, your code is not correct, it should be something closer to this:
$("input[type='button'][value='Agregar Pieza']").before("<p>new text</p>");
Live demo: http://jsfiddle.net/wKhap/
It isn't working because you need to import jQuery before using it. In order to do so, you need to add this tag:
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
Add this before any other references to scripts that use jQuery.

How to have a user input to Math.js

I want to be able to convert a user given amount to another quantity on a website using Math.js and an input box but whatever I try will not be able to get the users input from the input box labeled "convert" and change it. How could I achieve this?
http://jsfiddle.net/zFuNs/1/
<!DOCTYPE html>
<html>
<head>
<title>Convert</title>
<script type="text/javascript" src="https://raw.github.com/josdejong/mathjs/master/dist/math.js"></script>
</head>
<body>
<input type="text" id="convert"></input>
<script>
function print(value) {
document.write(math.format(value) + '<br>');
}
print(math.eval('"TEXT IN CONVERT BOX HERE" inch in cm'));
</script>
</body>
</html>
Try learning some basic JS, and some library like jQuery.
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on
your website.
jQuery takes a lot of common tasks that require many lines of
JavaScript code to accomplish, and wraps them into methods that you
can call with a single line of code.
jQuery also simplifies a lot of the complicated things from
JavaScript, like AJAX calls and DOM manipulation.
here is a working example of your question http://jsfiddle.net/zFuNs/3/
$('#convert').click(function () {
var cm = math.eval( $('#inch').val() + ' inch in cm' );
$('#cms').text(cm);
});

Beginner JavaScript: using src

EDIT:[Honestly this works fine you can read my edit comment below.]
So I am very new to JavaScript. This book I have tells me that I can write the script code in another file that has a .js extension. What it doesn't tell me is what should be in that .js extension.
<html>
<head>
<title>Title of Document</title>
<script src="path/to/file/fileName.js"></script>
</head>
<body>
The content of
your page goes here.
</body>
</html>
Lets say I wanted to make an alert message in the java script file. Inside the "fileName.js" would all I write be:
alert("This is an alert box");
and then save it and call it quits? Cause that is what I have so far and nothing doing.
EDIT:
Ok I want to add this in for anyone in trouble like I was. Turns out, this works perfectly. The comments below are a great help for further information. But the thing I did not realize was that on my Mac I needed to start the path to file at /Users. I feel dumb but at least I figured it out. Thanks all for your help.
Use " instead of ”:
<script src="path/to/file/fileName.js"></script>
^ ^
Generally your js files will have objects and Methods that are called/used from you main page.
So you html wiil look like :
<html>
<head>
<title>Title of Document</title>
<script src="path/to/file/fileName.js"></script>
</head>
<body onload="showAlert();">
The content of
your page goes here.
</body>
</html>
and you js will look like:
function showAlert(){
alert("This is an alert box");
}
Look into events and listeners. For example, if you want the alert to come up when the page loads, your html file would have:
<body onload="functionName()">
</body>
And you javascript file would have:
function functionName() {
alert("alert message");
}
Usually you would write your Javascript code as a series of functions that you can call whenever you need. So yes, you can write a single statement the way you did but most times its functions.

Categories

Resources