ReactJs Textfit in box with fixed size/variable fontsize - javascript

I would like to solve a Problem in ReactJs. The User can write text in a textbox and it gets printet insinde a box live. I now want the fontsize of the Text to get smaller when the limits of the box are reached.
How would i solve this in React?
thanks in advance
markus
I have found the solution in vanilla js and it looks a little like this:
const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');
function resize_to_fit() {
let fontSize = window.getComputedStyle(output).fontSize;
output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';
if(output.clientHeight >= outputContainer.clientHeight){
resize_to_fit();
}
}
function processInput() {
output.innerHTML =this.value;
output.style.fontSize = '100px'; // Default font size
resize_to_fit();
}
input.addEventListener('input', processInput);
warning! the above is not my code!

Related

Why my createdElement is doubling in reactjs useEffect()?

So my issue here is quite simple but you don't have to understand the others codes just only the useEffect() parts..
My custom mousecursor text is doubling when I tried to hover the text
here is the lines of codes.
const cursorIntro = document.querySelector(".cursor");
const options = document.querySelector(".introduction .nav-options");
options.addEventListener("mousemove", function s(e) {
var rect = options.getBoundingClientRect();
var x = e.clientX - rect.left; //x position within the element.
var y = e.clientY - rect.top;
cursorIntro.style.left = x + "px";
cursorIntro.style.top = y + "px";
});
function OnSelect() {
const optionsSelection = document.querySelectorAll(".options");
optionsSelection.forEach((elem, i) => {
// console.log(elem.children[1].children[0].children[0])
elem.children[1].children[0].children[0].addEventListener(
"mouseleave",
() => {
cursorIntro.removeChild(cursorIntro.lastChild);
// cursorIntro.innerHTML = ""
}
);
elem.children[1].children[0].children[0].addEventListener(
"mouseenter",
() => {
// elem.children[1].children[0].children[0].classList.add('')
const createElement = document.createElement("h4");
createElement.innerText =
elem.children[1].children[0].children[0].dataset.name;
cursorIntro.appendChild(createElement);
}
);
});
}
OnSelect();
As you see I have a custom mousecursor on it and because that is where I want to append the text when it hover the text elements.
This is inside the useEffect() when I'm calling it...but one that I wasn't sure is that I only call back once the addEventListener per each.
The reason I used createElement because if I used innerHTML without using a createElement I can't add another some items because my plan here is to added something more in mousecursor
THIS IS THE CODEPEN
go to index.js and replace StrictMode to React.Fragment, in dev mode react re-renders twice

Autofit multiple textarea's height to loaded content

I wrote a html/php page in order to update database content. The page has several forms (one for each db row I need to edit), and every form has several textarea fields.
I would like to fit every textarea's height to its content (as retrieved from db), using pure JavaScript (no jQuery).
I've found the following JS function:
function autoResize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
But how can I use it for every textarea field in the page? Is there a better way to achieve the goal?
Thanks!
UPDATED
Maybe this is a good solution:
var els = document.querySelectorAll('textarea');
Array.from(els).forEach((el) => {
var offset = el.offsetHeight - el.clientHeight;
el.style.height = 0;
el.style.height = el.scrollHeight + offset + 'px';
el.addEventListener('input', function() {
el.style.height = el.scrollHeight + offset + 'px';
});
});
Could it be done in a better way?
Check out this snippet:
<script>
var content = document.getElementsByClassName('db-content');
for(var i=0; i<content.length; i++){
content[i].style.height = 'auto';
content[i].style.height = content[i].scrollHeight + 'px';
}
</script>
You have to apply same class to all <textarea> (db-content in the above snippet) and add this script after them. In the script we are looking for all of those <textarea> by their class name and storing them in an array. Next we loop through the array and apply style to all <textarea>.

How to change a javascript variable with HTML?

I am making a chrome extension which adds icons to certain URLs, so I would like to make a slider to adjust the size of the icon in the popup.html.
The HTML of the slider looks like this:
<div class="slidecontainer">
<input type="range" min="1" max="3" value="2" class="slider" id="myRange">
</div>
But for the slider to work, it needs some javascript code.
In the javascript file, I made a variable called size. I need the javascript to change the size variable according to the position of the slider.
var size = "/images/icon16.png";
var imageURL = "chrome-extension://" + chrome.i18n.getMessage("##extension_id") + size;
So I am thinking of a script that checks for myRange, and if it is 1, 2, or 3, it sets size to corresponding string:
"/images/icon16.png"
"/images/icon48.png"
"/images/icon128.png"
The catch is that I don't know how to implement this in my code, so any help or explanation would mean the world to me ...
You could save your strings in an array:
var myPaths = [
"/images/icon16.png",
"/images/icon48.png",
"/images/icon128.png"
]
And access your slider input like this:
var slider = document.getElementById("myRange");
so that slider.value will be the value of the input.
You could listen out for the change event on the slider, and then set your size variable accordingly.
Full code:
var myPaths = [
"/images/icon16.png",
"/images/icon48.png",
"/images/icon128.png"
];
var size = "/images/icon16.png";
var slider = document.getElementById("myRange");
slider.addEventListener("change", updateSize);
function updateSize() {
size = myPaths[slider.value - 1];
}
In short: document.getElementById("myRange").value;.
You can read more about sliders and getting the value of the slider here. If you want to get the value every time the slider is utilised:
document.getElementById("myRange").addEventListener("input", (evt) => {
console.log(evt.target.value);
})
Attach an onchange event listener to the input tag.
Declare enum as follows:
let enum = {
1: "/images/icon16.png",
2: "/images/icon48.png",
3: "/images/icon128.png"
}
Write something like this in the callback:
var size,
imageURL;
let enum = {
1: "/images/icon16.png",
2: "/images/icon48.png",
3: "/images/icon128.png"
}
let inputrange = document.querySelector('input[type=range]');
inputrange.addEventListner("change", function() {
size = enum[inputrange.value];
imageURL = `chrome-extension://${chrome.i18n.getMessage("##extension_id") + size}` ;
}) ;

How to fix reverse text in javascript live syntax highlighting?

My script highlights the keywords but whenever it does, it messes with the string and does random things with the text like reverse it and mix it up.I was wondering if someone could tell me how to unreverse this text or move the cursor to the end of the contenteditable div or at most just fix it for me. I don't want any external libraries just javascript and jquery.
jsfiddle
JS Code:
function UnColor() {
var elem = document.getElementById("editor");
var text = elem.textContent;
elem.innerHTML = text;
}
function Color() {
UnColor();
var elem = document.getElementById("editor");
var code = elem.innerHTML;
code = code.replace("var","<span style='color:dodgerblue'>var</span>");
code = code.replace(/"(.*?)"/g,"<span style='color:green'>"$1"</span>");
code = code.replace(/<(.*?)>/g,"<span style='color:#F90'><$1></span>");
elem.innerHTML = code;
}
setInterval(Color,1000)
Thanks!
If the issue you're having is the cursor moving around while editing, you can fix that by grabbing the position of the cursor and putting it back at the end of the function. Do that by getting the selectionStart property of your editor textbox and then setting the selectionEnd property to that value after running the replacement.
Check out this answer for more information about selectionStart and selectionEnd.
Here's a simple code snippet from this answer that should get you rolling.
document.getElementById('target').addEventListener('input', function (e) {
var target = e.target,
position = target.selectionStart; // Capture initial position
target.value = target.value.replace(/\s/g, ''); // This triggers the cursor to move.
target.selectionEnd = position; // Set the cursor back to the initial position.
});
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />
This issue is coming as the textContent of editor id being equated to its innerHTML. So change the variable name like the JS code I was written here :
function UnColor() {
var elem = document.getElementById("editor");
var text = elem.textContent;
var elem2;
elem2.innerHTML = text;
}
function Color() {
UnColor();
var elem = document.getElementById("editor");
var code = elem.innerHTML;
code = code.replace("var","<span style='color:dodgerblue'>var</span>");
code = code.replace(/"(.*?)"/g,"<span style='color:green'>"$1"</span>");
code = code.replace(/<(.*?)>/g,"<span style='color:#F90'><$1></span>");
var elem2;
elem2.innerHTML = code;
}
setInterval(Color,1000)

I want to change css style using javascript

I want to append font style and type in textarea as per user requirement. I tried but my script is not working...
function run() {
var fontType = document.getElementById("font_type").value;
var fontSize = document.getElementById("font_size").value;
var textArea = document.getElementById("msg");
//alert(fontType+fontSize);
textArea.style.font-size = fontSize ;
textArea.style.font-family = fontType;
}
Try the following instead:
textArea.style.fontSize = fontSize ;
textArea.style.fontFamily = fontType;
Otherwise your JavaScript is evaluated as:
textArea.style.font - size = fontSize;
textArea.style.font - family = fontType;
... which doesn't make any sense (and so throws a ReferenceError: Invalid left-hand side in assignment).
This conversion (something-something to somethingSomething) is consistent when changing all style properties in JavaScript (border-radius -> borderRadius etc).
Try:
textArea.style.fontSize = fontSize ;
textArea.style.fontFamily = fontType;

Categories