Can you change css code of a selected text input using JS - javascript

Let me be clear. I am asking how to change CSS code on a selected text. Not like a checkbox or anything of that sort.
var txtarea = document.getElementById("txtarea");
var selected = window.getSelection();
if (selected) {
//Change CSS Code
}
Thanks in advance.

You can achieve a new styling using an active class, so you will be able to use it in every element with an ID of txtarea by clicking on the element you will toggle between the common txtarea and txtarea active
If you have an element, for example a textarea tag with an ID called txtarea
document.querySelector('#txtarea').addEventListener('click', ctrlAddItem);
Now you have to create a loop:
document.querySelectorAll("#txtarea").forEach(function () {
this.addEventListener("click", ctrlAddItem);
});
Now you have to create a function, so everytime you click on element it will add or remove the ID active:
var ctrlAddItem = function(e) {
e.target.classList.toggle("active");
}

you can do it like this:
var txtarea = document.getElementById("txtarea");
txtarea.style.width = '200px';
txtarea.style.height = '200px';
txtarea.style.color = 'grey';
txtarea.style.fontSize = '18px';
keep in mind that if the selected element doesn't exist in the DOM JavaScript will throw an error, so you don't need to use an if statement to test if it exists

Related

How to getSelection() within a specific div?

I have a contenteditable div (with id 'editor1') that allows users to input text. There is then a function that allows them to color any highlighted text. My js uses window.getSelection().getRangeAt(0), but the issue with this is that they can highlight words outside of the div and their color will change as well. So far; I've tried:
function red(){
{
var getText = document.getElementById("editor1").innerHTML;
var selection = getText.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.color = "red";
span.appendChild(selectedText);
selection.insertNode(span);
}
}
Fiddle: https://jsfiddle.net/xacqzhvq/
As you can see, if I highlight "this will become red as well", I can use the button to make that red too.
How can I only color the highlighted text only within the editor1 div?
You are able to get the node element from the selection using .baseNode. From there you can get the parent node and use that for comparison.
function red(){
// If it's not the element with an id of "foo" stop the function and return
if(window.getSelection().baseNode.parentNode.id != "foo") return;
...
// Highlight if it is our div.
}
In the example below I made the div have an id that you can check to make sure it's that element:
Demo
As #z0mBi3 noted, this will work the first time. But may not work for many highlights (if they happen to get cleared). The <span> elements inside the div create a hierarchy where the div is the parent elements of many span elements. The solution to this would be to take traverse up through the ancestors of the node until you find one with the id of "foo".
Luckily you can use jQuery to do that for you by using their .closest() method:
if($(window.getSelection().baseNode).closest("#foo").attr("id") != "foo") return;
Here is an answer with a native JS implemented method of .closest().
Are you looking for this,
//html
<body>
<p id='editor1'>asdf</p>
<button onclick='red()'>
RED
</button>
</body>
//JavaScript
window.red = function(){
//var getText = document.getElementById("editor1").innerHTML;
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement("span");
span.style.color = "red";
span.appendChild(selectedText);
selection.insertNode(span);
}
Plunker: https://plnkr.co/edit/FSFBADoh83Pp93z1JI3g?p=preview
Try This Code :
function addBold(){
if(window.getSelection().focusNode.parentElement.closest("#editor").id != "editor") return;
const selection = window.getSelection().getRangeAt(0);
let selectedParent = selection.commonAncestorContainer.parentElement;
let mainParent = selectedParent;
if(selectedParent.closest("b"))
{
//Unbold
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("b");
span.appendChild(selection.extractContents());
selection.insertNode(span);
mainParent.normalize();
}
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
<div id="editor" contenteditable="true">
You are the programmers of the future
</div>
<button onclick="addBold()">Bold</button>
I got the code and added my edits from those following answers :
Bold/unbold selected text using Window.getSelection()
getSelection().focusNode inside a specific id doesn't work

jQuery show new element after dom change

I found many ways to operate on new elements after DOM change but all works with events. I just want on click hide element 1 than replace it with 2 with display:none and show it.
My code so far:
/*
* EDIT COMMENT
*/
jQuery(document).on('click',options.targets.container+' '+options.targets.comment_edit, function(e){
e.preventDefault();
var target = e.target;
target = jQuery(target).parent();
var comment_content = jQuery(target).find('.comment_content');
var comment_content = jQuery(comment_content).text();
jQuery(target).find('.comment_content').hide(400,function(){
jQuery(target).find('.comment_content').replaceWith('<textarea style="display:none" class="'+options.targets.comment_edit_form.replace('.','')+'">'+comment_content+'</textarea>');
//not working
jQuery(target).delay(400).find(options.targets.comment_edit_form.replace('.','')).show(400)
console.log(jQuery(target).find(options.targets.comment_edit_form.replace('.','')))
});
})
I want to show new element just after i do replacing.
Problems are 2:
1: I can't get new element with jquery because it is added;
2: I can't display it after other function is done.
Here's how I created an element:
var dialogDiv = document.createElement("div");
$("body").append(dialogDiv);
$(dialogDiv).html('<p>' + text + '</p>');
Search element after insertion.
Modify your code as
jQuery(document).on('click',options.targets.container+' '+options.targets.comment_edit, function(e){
e.preventDefault();
var target = e.target;
target = jQuery(target).parent();
var comment_content = jQuery(target).find('.comment_content');
var comment_content = jQuery(comment_content).text();
jQuery(target).find('.comment_content').hide(400,function(){
jQuery(target).find('.comment_content').replaceWith('<textarea style="display:none" class="'+options.targets.comment_edit_form.replace('.','')+'">'+comment_content+'</textarea>');
//show after ( put your code here )
jQuery(target).find('textarea').show();
});
})
http://jsbin.com/pirinocuku/edit?html,js,output
What i did wrong was
jQuery(target).find(options.targets.comment_edit_form.replace('.','')).show(400)
options.targets.comment_edit_form is class and i remove . from it so it couldnt find an element;
Changed to:
jQuery(document).on('click',options.targets.container+' '+options.targets.comment_edit, function(e){
e.preventDefault();
var target = e.target;
target = jQuery(target).parent();
var comment_content = jQuery(target).find('.comment_content');
var comment_content = jQuery(comment_content).text();
jQuery(target).find('.comment_content').hide(400,function(){
jQuery(target).find('.comment_content').replaceWith('<textarea style="display:none" class="'+options.targets.comment_edit_form.replace('.','')+'">'+comment_content+'</textarea>');
jQuery(target).find(options.targets.comment_edit_form.replace('.','')).show(400)
});
})
My bad, sorry guys

Create List Item From Rich Text Field Content

I want to take the user input text from this div and input tag I've got:
<input id="title" placeholder="Title (Optional)">
<div class="editor" contenteditable></div>
The div is a rich text field that I've put in place of a regular textarea tag
and create a list item inside a <ul> tag.
Here is the javascript I've got, but is not working...
(works just fine with regular text area, but I get nothing with the rich text form)
/*------POST SUBMIT JS------*/
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementsByClassName('editor').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
Here is the demo I'm working on
Here is the demo using a textarea tag
getElementsByClassName('editor') is going to return an array of elements with the class editor, so you can't just do .value, you need to get the first element in the array.
Also, since it's a div, I think you want to use textContent, so it'll look like this
var inputText = document.getElementsByClassName('editor')[0].textContent
for the input type you have to write following into your javascript:
var input_val = getElementsByClassName('title').value;
for the div you have to write following into your javascript:
var div_val = getElementsByClass('editor').value;
I hope this will work

Change the onClick function to target the edit buttons

I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element

use javascript to dislay a form field as text until clicked on

I have got this working with the start point as a span, but I want to have the form still function if javascript is disabled in the browser this is how I had it working originally. I'm still very new to javascript, can someone lend a hand please.
window.onload = function() {
document.getElementById('container').onclick = function(event) {
var span, input, text;
// Get the event (handle MS difference)
event = event || window.event;
// Get the root element of the event (handle MS difference)
span = event.target || event.srcElement;
// If it's a span...
if (span && span.tagName.toUpperCase() === "SPAN") {
// Hide it
span.style.display = "none";
// Get its text
text = span.innerHTML;
// Create an input
input = document.createElement("input");
input.type = "text";
input.size = Math.max(text.length / 4 * 3, 4);
span.parentNode.insertBefore(input, span);
// Focus it, hook blur to undo
input.focus();
input.onblur = function() {
// Remove the input
span.parentNode.removeChild(input);
// Update the span
span.innerHTML = input.value;
// Show the span again
span.style.display = "";
};
}
};
};
Best way to do this would be to show the input first, then quickly swap it out when the page loads, then swap it back when the user clicks.
You might also consider using the form element the whole time, but just changing CSS classes on it to make it look like normal text. This would make your UI cleaner and easier to maintain in the future.
Then just put the input fields there from the start, and hide them with a script that runs when the form has loaded. That way all the fields will be visible if Javascript is not supported.
I think your best option would be to wrap a form with noscript tags which will fire when Javascript is disabled in a browser. If they display even while in the noscript tags then just set them as not visible with Javascript.
if you have jQuery, something like this should work.
function makeElementIntoClickableText(elm){
$(elm).parent().append("<div onClick='switchToInput(this);'>"+ elm.value +"</div>");
$(elm).hide();
}
function switchToInput(elm){
$(elm).prev().prev().show();
$(elm).hide();
}
makeElementIntoClickableText($("input")[0]);
use the readonly attribute in the input elements:
<input type="text" readonly />
And then remove that attribute with JavaScript in the onclick event handler, reassigning it on blur:
var inputs = document.getElementsByTagName('input');
for (i=0; i < inputs.length; i++) {
inputs[i].setAttribute('readonly',true);
inputs[i].onclick = function(){
this.removeAttribute('readonly');
};
inputs[i].onblur = function(){
this.setAttribute('readonly',true);
};
}
JS Fiddle demo.

Categories