No scrollbar in Chrome, but in Firefox and IE, it doesn't disappear although the element width is 0:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Textarea Scrollbar</title>
<style>
textarea {
height: 200px;
width: 0;
margin: 0;
border: 0;
padding: 0;
}
</style>
</head>
<body>
<textarea id="textarea">
Hello, world!
...
</textarea>
<input type="text" value="0" id="input" oninput="resize();">
<script>
function resize() {
document.getElementById('textarea').style.width = document.getElementById('input').value + 'px';
}
</script>
</body>
</html>
DEMO
What's the reason? What's a cross-browser solution so the textarea behaves like in Chrome?
Try overflow:hidden; in the css for the text area attributed ID
EDIT
DEMO
Javascript
//this function attaches eventListener to the element and it is compatible with legacy browsers as well
function attach(element,listener,ev,tf){
if(element.attachEvent) {
//support for older IE (IE7 inclusive)
element.attachEvent("on"+listener,ev);
}else{
//modern browsers
element.addEventListener(listener,ev,tf);
}
}
var newInterval; //we use this to set interval and check say every 200 milliseconds
//whether the *height* of our *textarea* has changed and if it has
//than we set its *overflow* to *auto*, so the *scrollbar* will be
//visible, but when the *height* is *less or equal to 200* we set
//its *overflow* to *hidden*, so the *scrollbar* isn't visible!
var textarea = document.getElementById('textarea');
var input = document.getElementById('input');
//here we check if the value of our input element has changed than we change the width of our textarea
attach(input,'input',function(){
textarea.style.width = input.value + 'px';
},false);
//when our textarea recieves focus (is clicked on) we start running the interval and
//check every 200 milliseconds if the height of the textarea is equal or greater than
//200px we set its overflow to auto so the scrollbar becomes visible, and when the
//height is equal or less than 200px we set our textareas overflow to hidden, so no
//scrollbar is visible
attach(textarea,'focus',function(){
newInterval = setInterval(function(){
height = textarea.scrollHeight;
if(height>=200){
textarea.style.overflow = 'auto'
}else textarea.style.overflow = 'hidden';
},200);
},false);
//here we clear our interval, as our textarea has lost focus
// and there is no need to further run our interval
attach(textarea,'blur',function(){ clearInterval(newInterval); },false);
HTML
<textarea id="textarea">
Hello, world!
...
</textarea>
<input type="text" value="0" id="input" oninput="resize();">
CSS
textarea{
height: 200px;
width: 0;
margin: 0;
border: 0;
padding: 0;
overflow:hidden;
border:1px solid red;
}
Related
I am trying to make an automatic scrolling marquee using javascript and CSS but, I also want to be able to manually scroll the marquee with the mouse wheel. The marquee functions as expected ie. it scrolls automatically and loops well but I can't figure out how to incorporate manual scrolling. Here is the code that I am using. Any ideas?
<doctype HTML>
<body onload="init()">
<main>
<div id="marquee_replacement" class="scrollbar" onmouseout="startit();" onmouseover="stop();">
<p>some text some text some text some text some text some text some text some text</p>
<p>some text some text some text some text some text some text some text some text</p>
<p>some text some text some text some text some text some text some text some text</p>
<p>images are also present</p>
<p class="spacer"></p>
</div>
<script type="text/javascript">
//
var speed = 2; // change scroll speed with this value
/**
* Initialize the marquee, and start the marquee by calling the marquee function.
*/
function init() {
var el = document.getElementById("marquee_replacement");
el.style.overflow = 'hidden'; //issue is fixed by setting this to auto
scrollFromBottom();
}
var go = 0;
var timeout = '';
/**
* This is where the scroll action happens.
* Recursive method until stopped.
*/
function scrollFromBottom() {
clearTimeout(timeout);
var el = document.getElementById("marquee_replacement");
if (el.scrollTop >= el.scrollHeight - 150) {
el.scrollTop = 0;
};
el.scrollTop = el.scrollTop + speed;
if (go == 0) {
timeout = setTimeout(scrollFromBottom, 50);
};
}
/**
* Set the stop variable to be true (will stop the marquee at the next pass).
*/
function stop() {
go = 1;
}
/**
* Set the stop variable to be false and call the marquee function.
*/
function startit() {
go = 0;
scrollFromBottom();
}
</script>
<!--CSS for Marquee-->
<style type="text/css">
#marquee_replacement.scrollbar {
width: auto;
height: 150px;
overflow-y: scroll; /*issue is fixed by setting this to auto*/
}
.scrollbar::-webkit-scrollbar {
display: none;
}
#marquee_replacement {
-ms-overflow-style: none;
/* IE and Edge */
scrollbar-width: none;
/* Firefox */
}
#marquee_replacement p.spacer {
height: 150px;
}
</style>
</main>
</body>
Edit:
Sorry for the newbie mistake of not providing a minimal reproducible example. I will update the code above to provide an MREX so that the issue is easier to understand for future readers. Also, I solved the issue. If I set the overflow values in both CSS and javascript portions to auto instead of scroll and hidden respectively it works as an auto-scrolling marquee and manual scrolling text box.
setTimeout takes a function, not a string with code. Do it like this: setTimeout(scrollFromBottom, 50)
I figured it out. If anyone needs this in the future I had to set el.style.overflow = 'auto';to auto instead of hidden and set the CSS overflow to overflow-y: auto; to auto instead of scroll. Now it scrolls automatically and manually!
This is my html code for displaying a editable textbox and is used as a "memo" element inside a webpage (inside a div tag).
contenteditable="true" name="choice1" class="textfield" max="872">Enter your Memo Here!
CSS:
.textfield {
max-width: 800px;
width: 800px;
border: 1px solid black;
padding: 8px;
margin: 20px;
float:right;
position: relative;
}
Javascript:
var textfields = document.getElementsByClassName("textfield");
for(i=0; i<textfields.length; i++){
textfields[i].addEventListener("keypress", function(e) {
if(this.innerHTML.length >= this.getAttribute("max")){
e.preventDefault();
return false;
}
}, false);
}
However when I fill the editable div area with alot of spaces (" "), it takes less than the declared 872 characters to reach the maximum limit. Does anyone know why and have a solution? Thanks.
Use textContent instead of innerHTML.
The textContent property sets or returns the textual content of the specified node, and all its descendants.
The innerHTML property sets or returns the HTML content (inner HTML) of an element.Which will include tags
In the below example I have set the max as 20
var textfields = document.getElementsByClassName("textfield");
for (i = 0; i < textfields.length; i++) {
textfields[i].addEventListener("keypress", function(e) {
if (this.textContent.length >= this.getAttribute("max")) {
e.preventDefault();
console.log('max reached') ;
return false;
}
}, false);
}
<div contenteditable="true" name="choice1" class="textfield" max="20">Enter your Memo Here!</div>
I can't quite find a clear answer on this, and excuse me if there is one I've missed.
I want my text input widths to automatically adjust to the size of the content within them. First with placeholder text than the actual text someone inputs.
I've created the below as an example. Currently, the boxes are far bigger than my placeholder text, causing huge amounts of white space, and it's obviously the same thing when I type in something.
I've tried width auto, some jQuery, and twine and bubble gum I found on the internet. But nothing has worked yet. Any thoughts? Thanks!
HTML:
<span><p>Hello, my name is </p></span>
<span><input type="text" id="input" class="form" placeholder="name"></span>
<span><p>. I am </p></span>
<span><input type="text" id="input" class="form" placeholder="age"></span>
<span><p> years old.</p></span>
CSS:
.form {
border: 0;
text-align: center;
outline: none;
}
span {
display: inline-block;
}
p {
font-family: arial;
}
Fiddle
One possible way:
[contenteditable=true]:empty:before {
content: attr(placeholder);
color:gray;
}
/* found this online --- it prevents the user from being able to make a (visible) newline */
[contenteditable=true] br{
display:none;
}
<p>Hello, my name is <span id="name" contenteditable="true" placeholder="name"></span>. I am <span id="age" contenteditable="true" placeholder="age"></span> years old.</p>
Source for CSS: http://codepen.io/flesler/pen/AEIFc.
You'll have to do some trickery to pick up the values if you need the values for a form.
Use onkeypress even
see this example :http://jsfiddle.net/kevalbhatt18/yug04jau/7/
<input id="txt" placeholder="name" class="form" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"></span>
And for placeholder on load use jquery and apply placeholder
size in to input
$('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px');
Even you can use id instead of input this is just an example so that I
used $(input)
And in css provide min-width
.form {
border: 1px solid black;
text-align: center;
outline: none;
min-width:4px;
}
EDIT:
If you remove all text from input box then it will take placeholder value using focusout
Example: http://jsfiddle.net/kevalbhatt18/yug04jau/8/
$("input").focusout(function(){
if(this.value.length>0){
this.style.width = ((this.value.length + 1) * 8) + 'px';
}else{
this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';
}
});
input.addEventListener('input', event => event.target.style.width = event.target.scrollWidth + 'px');
Unfortunately this will only increase the size of the input. If you delete characters the size will not decrease. For some use cases this is perfectly fine.
Kevin F is right, there is no native way to do it.
Here is a one way to do it if you really want it to happen.
In the code, there is an invisible span where the text is placed. Then we retrieve the width of the span.
https://jsfiddle.net/r02ma1n0/1/
var testdiv = $("#testdiv");
$("input").keydown( function(){
var ME = $(this);
//Manual Way
//var px = 6.5;
//var txtlength = ME.val().length;
//$(this).css({width: txtlength * px });
testdiv.html( ME.val() + "--");
var txtlength = testdiv.width();
ME.css({width: txtlength });
});
Try with 'size' attribute.
This will work even when you clear the text .
Need jQuery to work this
<div>
<input id="txt" type="text" style="max-width: 100%;" placeholder="name">
</div>
<script>
$(document).ready(function() {
var placeholderLen = $('#txt').attr('placeholder').length;
// keep some default lenght
placeholderLen = Math.max(5, placeholderLen);
$('#txt').attr('size', placeholderLen);
$('#txt').keydown(function() {
var size = $(this).val().length;
$(this).attr('size', Math.max(placeholderLen, size));
});
});
</script>
I am attempting to create a function where by a button is clicked and the background image is selected for a div. Here is what I have started below but it does not seem to work can anyone point out where Im going wrong... :)
<style type="text/css">
#txt{
width: auto;
height: auto;
border: solid #000;
}
</style>
<script type="text/javascript">
function backg1(){
var test = new string ();
test = document.getElementById('txt');
test.style.backgroundImage="url('cloud.jpg')";
}
</script>
</head>
<body>
<div id="txt">
<input type="button" value="BG1" onclick="backg1()"/>
</div>
Since your <div> originally contains nothing but the button input, it has no size outside the boundaries of that button. You will need to set an explicit width and height (along with position: relative) to see the background.
I would recommend setting them to the same dimensions as your image.
/* in the CSS */
#txt{
/* use the width, height of your image */
width: 400px;
height: 250px;
position: relative;
border: solid #000;
}
Or if you need to set them dynamically:
function backg1() {
test = document.getElementById('txt');
test.style.backgroundImage="url('cloud.jpg')";
// <div> needs a width & height for the background image to be visible outside the
// bounds of the one element contained in the div.
test.style.width = "400px";
test.style.height = "250px";
test.style.position = "relative";
}
There is a javascript error at this line.
var test = new string ();
You can make it like var test = new String(); Then it should work.
Moreover, i observed that you are creating string object and then you are overriding with DOM object. Not sure why it so like that. You can just create a variable like var test;
I am facing a problem with setting cursor position in a contentEditable div and seek some assistance.
I have already looked at several SO and other online solutions without success, including:
jquery Setting cursor position in contenteditable div, and
Set cursor position on contentEditable <div> and many other online resources.
Basically, we are using a Telerik Editor with the contentAreaMode set to DIV which forces it to use a contentEditable div instead of an iFrame. When a user clicks in the editor, we wish to be able to move the cursor to the click point so the user may enter/edit content wherever they wish in the editor. Using the example code below, I am able to set the cursor position in FF, Chrome, and IE9 to AFTER the inner div. However, in IE8 (which falls into the else if (document.selection) block), I am unable to get the cursor position to move after the div, so any typed text ends up either before or inside the div - never after. I would be GREATLY appreciative of any help.
ADDITIONAL INFO: Need this to work in IE8 standards document mode - NOT in Quirks mode (which does work).
UPDATE: Here is a jsfiddle of the issue to play with: http://jsfiddle.net/kidmeke/NcAjm/7/
<html>
<head>
<style type="text/css">
#divContent
{
border: solid 2px green;
height: 1000px;
width: 1000px;
}
</style>
<script type="text/javascript">
$(document).ready(function()
{
$("#divContent").bind('click', function()
{
GetCursorPosition();
});
$("#divContent").bind('keydown', function()
{
GetCursorPosition();
});
});
function GetCursorPosition()
{
if (window.getSelection)
{
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
cursorPos = findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset;
$('#htmlRadEdit_contentDiv').focus();
selObj.addRange(selRange);
}
else if (document.selection)
{
var range = document.selection.createRange();
var bookmark = range.getBookmark();
// FIXME the following works wrong when the document is longer than 65535 chars
cursorPos = bookmark.charCodeAt(2) - 11; // Undocumented function [3]
$('#htmlRadEdit_contentDiv').focus();
range.moveStart('textedit');
}
}
function findNode(list, node)
{
for (var i = 0; i < list.length; i++)
{
if (list[i] == node)
{
return i;
}
}
return -1;
}
</script>
</head>
<body>
<div id="divContent" contentEditable="true">
<br>
<div style="background-color:orange; width: 50%;">
testing!
</div>
</div>
</body>
</html>
Using Rangy (disclosure: I'm the author) works for me in IE 7 and 8 in the window load event. Trying to move the caret when the user clicks on an editable element is a bad idea: it conflicts with default browser behaviour hence may not work, and does not do what he user expects (which is to place the caret at or near where they clicked).
<html>
<head>
<style type="text/css">
#divContent
{
width: 1000px;
height: 1000px;
border: solid 2px green;
padding: 5px
}
</style>
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-core.js"></script>
<script type="text/javascript">
window.onload = function() {
rangy.init();
var el = document.getElementById("divContent");
el.focus();
var range = rangy.createRange();
range.setStartAfter(el.getElementsByTagName("div")[0]);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
};
</script>
</head>
<body>
<div id="divContent" contentEditable="true">
<br>
<div style="background-color:orange; width: 50%;">
testing!
</div>
</div>
</body>
</html>