Is there a way to maintain the div scroll position on a postback, without using asp? So far I've only found solutions using asp.
http://blogs.x2line.com/al/articles/156.aspx
<!doctype html>
<html>
<head>
<title></title>
<script language="javascript">
// function saves scroll position
function fScroll(val)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = val.scrollTop;
}
// function moves scroll position to saved value
function fScrollMove(what)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(what).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="fScrollMove('div_scroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br>
<div id="div_scroll" onscroll="fScroll(this);" style="overflow:auto;height:100px;width:100px;">
.. VERY LONG TEXT GOES HERE
</div>
</form>
</body>
</html>
Maybe this javascript code works for you
function loadScroll ()
{
var m = /[&?]qs\=(\d+)/.exec (document.location);
if (m != null)
myDiv.scrollTop = parseInt (m[1]);
}
function saveScroll ()
{
var form = document.getElementById ("myForm");
var sep = (form.action.indexOf ("?") == -1) ? "?" : "&";
form.action += sep + "qs=" + myDiv.scrollTop;
}
Now, you can watch for the "submit" event to save the position in the "action" attribute:
document.getElementById ("myForm").addEventListener ("submit", saveScroll, false);
And in your BODY tag...
<body onload="loadScroll ();">
....
</body>
I can't test the code right now, but I think you get the idea.
Related
So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))
I am trying to develop a braces auto completion feature in a text box. I tried the javascript replace function on the textbox. But i am getting a weird output from the function. Here's the code i am work on.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type ="text" id="textbox">
</body>
</html>
Javascript:
var element = document.getElementById('textbox');
element.oninput = function(){
var code = (function(){
var val = element.value;
element.value = val.replace(/\{/ , "{}");
})();
};
When i type a single { brace i am getting {} , when i type more than 1 i am getting {}}}{{ and it goes on .. sometimes my browser freezes when i try to clear the braces.
Here's the js bin link JSBIN
The problem is that you are always replacing { with {}, even if the bracket has already been matched. You should instead ensure it was not with negative lookahead: /\{(?!\})/
To fix the backspace issue, you should instead be using an event which can tell you which key was pressed like onkeyup and add a guard clause. Expanding on #Andi's idea, I also added exclusion for the arrow keys so you won't be forced to the end of the textbox when you want to navigate through the text:
var element = document.getElementById('textbox');
element.onkeyup = function(){
if([8, 37, 39].indexOf(event.which) != -1)
return false;
var code = (function(){
var val = element.value;
element.value = val.replace(/\{(?!\})/g, "{}");
})();
};
Your regex matches '{', you should exclude all '{}':
Snippet: [regex : /(?!{})\{/ ]
var element = document.getElementById('textbox');
element.oninput = function() {
var code = (function() {
var val = element.value;
element.value = val.replace(/(?!{})\{/, "{}");
})();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="textbox">
</body>
</html>
Update (With Backspace working):
Need to use keyboard event so that we can get keycode of the key pressed. Use onkeyup
var element = document.getElementById('textbox');
element.onkeyup = function(e) {
if (e.which != 8) {
var val = element.value;
element.value = val.replace(/(?!{})\{/, "{}");
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="textbox">
</body>
</html>
Regexs may become heavy for an autocompletion tool, especially with negative lookaheads.
Actually, you do not have to look for braces at each input, just test the character typed with onkeypress event.
And you should also put the caret into the braces, otherwise you have still one keystroke because you have to move back :)
var element = document.getElementById('textbox');
element.onkeypress = function(evt){
switch(String.fromCharCode(evt.which)){
case "{":
var currentCaretPosition= this.selectionStart;
var text= this.value;
this.value= text.slice(0, currentCaretPosition)+
"{\n\t\n}"+
text.slice(currentCaretPosition,text.length );
this.setSelectionRange( currentCaretPosition+3, currentCaretPosition+3 );
evt.preventDefault();
}
};
#textbox{
border:inset 1px #aaa;
width:80vw;
height:80vw;
margin:2vw;
padding:0.5vw
}
<textarea id="textbox">
function test()
</textarea>
The whole sting is evaluated each time the function is called.
{ -> {}
if you now add another } you get {}}{}
use val.replace(/\{$/ , "{}");
The $ only evaluates the last character. Here you can try to build regex queries:
https://regex101.com/r/iU4xT9/1
PS: Maybe it gets weirds when you delete the last } you could only call the function, when you add characters and ignore the delete key.
var element = document.getElementById('textbox');
element.onkeyup = function(event){
if(event.which == 8)
return false
var code = (function(){
var val = element.value;
element.value = val.replace(/\{$/ , "{}");
})();
};
Im trying to make an 'online' (HTML document) file that has an input to solve math, and I need a way to type in the numbers, and insert a 'solve me' button. I have the button, and the form by ID and class as well.
This is what I inserted into a "try it" prompt box through w3schools.com site, tried looking almost everywhere within that site to try to input it in.
<div id="A"></div>
<div id="B"></div>
<script>
var A = 1;
var ele = document.getElementById('A');
var y = 2;
var z = A + y;
document.getElementById("demo").innerHTML = z;
</script>
Is there a way to do this? And thank you guys for your help!
<!DOCTYPE html>
<html>
<body>
<input id="A"/>
<input id="B"/>
<div id="demo"></div>
<button onclick="add();">ADD</button>
<script>
function add () {
var A = document.getElementById('A').value *1;
var B = document.getElementById('B').value *1;
var z = A + B;
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
Hope this helps you, here you need to use input to have a user editable field,a div as you guessed to display your answer and button which triggers some logic.
I'm trying to make a program where if you for example type in "less" in the textarea the output should show "<". What is the best way to do this?
This is how far I've gotten:
<!doctype html>
<html lang="en">
<head>
<title>Group 7 - Deckcode to JavaScript</title>
</head>
<body>
<h1>Group 7 - Deckcode to JavaScript</h1>
<p>Input your deckode below:</p>
<textarea id="myTextarea"></textarea>
<button type="button" onclick="myFunction()">Translate</button>
<p id="demo"></p>
<script>
function myFunction() {
var input
if (myTextarea == "less") {
console.log("<");
}
}
</script>
</script>
</body>
</html>
You're trying to fish values out of the DOM incorrectly. Use document.getElementById to locate the element in the DOM, and take its value for the value you require.
function myFunction() {
var textAreaValue = document.getElementById("myTextarea").value;
if (textAreaValue == "less") {
console.log("<");
}
}
I suggest using an object like this:
var translations = {};
translations["less"] = "<";
translations["greater"] = ">";
And then in your function you do like this:
function myFunction() {
var value = document.getElementById("myTextarea").value;
console.log(translations[value] ? translations[value] : "No translation found");
}
It would also be easy to add more translations e.g. based on data from a database or similar.
as and alternative to IF-condition, you can use
if (textAreaValue.indexOf("less") > -1) {
console.log("<");
}
so if the text area contains "less" text then the console prints "<"
indexOf method
Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>