My problem is simple but I'm new to jquery and css so I don't really know what I'm doing. I have a css file style.css and this is what's in it.
keyword {
font-size: 12px;
color: #0000FF;
}
stringWord {
font-size: 12px;
color: #ff6a00;
}
I'm trying to change text inside of a text area so here is where that is declared.
<div class="DivWithScroll" id="my_text" contenteditable="true"
onkeypress="return myKeyPress(event)" onkeydown="return onKeyDown(event)">
In my jquery code I want it to go to the css file of keyword and change the color of the text.
This is what I have so far but it's not working properly
for (var i = 0; i < reservedKeyWords.length; i++) {
if ( lastWordTyped == reservedKeyWords[i] ) {
console.log(lastWordTyped + "::" + reservedKeyWords[i]);
$('DivToScroll').css("keyword");
return;
}
}
`
Like I said I'm new to all of this so any help is greatly appreciated.
Instead of .css('keyword') use .addClass('keyword').
Also note that your jQuery selector is targeting 'DivToScroll' rather than 'DivWithScroll' and you may want to change the jQuery selector to be
$('#my_text')
to reference the div by ID.
Related
I'm searching online and I didn't find anything.
I'm trying to update the placeholder color of a textbox using javascript, but how can I do that?
I have a color picker and the color is changing.
If I have something like this in my CSS, how can I update it?
::placeholder {
color: red;
}
<input placeholder="placeholder" />
Is there a javascript command to edit this?
Something like
document.getElementById('text').style.placeholderColor = newColor;
Use CSS variables. You can also target only the needed element
function update() {
document.querySelector('input[type=text]').style.setProperty("--c", "blue");
}
::placeholder {
color: var(--c, red);
}
<input type="text" placeholder="I will be blue">
<input type="number" placeholder="I will remain red">
<button onclick="update()">change</button>
CSS variables are useful when it comes to modify pseudo elements that you cannot access with JS such as :before/:after/::placeholer/::selection, etc. You simply define your custom property that you can easily update on the main element and the pseudo element will inherit it.
Related : Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery
As stated in the other answers, you cannot change pseudo-element styles inline. However, you can modify the CSS rule in the <style> itself, and you don't need a browser support ing CSS variables for that. Access the stylesheet and either get the existing rule or insert your own, then play with its style declarations like you would with an element .style:
const {sheet} = Object.assign(document.head.appendChild(document.createElement("style")), {type: "text/css" });
const placeholderStyle = sheet.rules[sheet.insertRule("::placeholder {}")].style;
placeholderStyle.color = "red";
Object.assign(document.body.appendChild(document.createElement("input")), {
type: "button", value: "Color!", onclick() {
placeholderStyle.color = "#"+Math.round(Math.random()*0xFFF).toString(16).padStart("0",3);
}});
<input placeholder="placeholder" />
There is another approach, but it's somewhat hacky: use JS to append more CSS to the end of the body. Browsers will override current CSS with the newest CSS, assuming the rules are identical.
function changeColor(toColor) {
addCSS = document.createElement('style');
addCSS.innerHTML = "::placeholder { color: " + toColor + "; }";
document.body.append(addCSS);
}
::placeholder { color: green; }
<input type="text" placeholder="placeholder">
<button onclick="changeColor('red')">red</button>
<button onclick="changeColor('blue')">blue</button>
The snippet below works without needing to make any changes to any existing CSS. You would need to modify it to work with your color picker, but hopefully this will give you something to start with.
const placeholder = document.createElement("style");
placeholder.innerHTML = `::placeholder { color:red;font-weight:bold;font-size:1.25rem;} #plchld { font-size:1.25rem;text-align:center; } `;
const plchld = document.getElementById("plchld");
plchld.addEventListener("click", function () {
plchld.setAttribute("placeholder", "Now I'm Bright Red!");
document.form.appendChild(placeholder);
});
plchld.addEventListener("blur", function () {
plchld.setAttribute("placeholder", "now I'm a dreary gray again...");
document.form.removeChild(placeholder);
});
<form name="form" action="">
<input type="text" id="plchld" size="28" placeholder="I'm currently a dreary shade of gray...">
</form>
If the placeholder color semantics depends on some state, it can be set indirectly
::placeholder { color: green; }
.warn::placeholder { color: red; }
<input id="test" placeholder="hello">
<button onclick="test.classList.toggle('warn')">Warning!</button>
In many cases this doesn't require javascript at all:
::placeholder { color: green; }
.color::after { content: 'green'; }
:checked + .color + ::placeholder { color: red; }
:checked + .color::after { content: 'red'; }
<input type="checkbox" id="color01">
<label class="color" for="color01">Color: </label>
<input placeholder="hello">
I am building a simple chat bot.On each new message received from the server, a new HTML element is created and pushed to the browser. So, for example, message 1 will be:
<div class="message-computer"><p>Hi, how are you?</p></div>
Then you (the user) types/sends a message, which shows up as:
<div class="message-user"><p>I am good, thanks!</p></div>
and so on and so forth. I created a slider to change the size of the text being sent to/from the chat bot. It now works, but it only edits EXISTING HTML elements. New messages sent to/from the server are still in the original size.
$('input').on('change', function() {
var v = $(this).val();
$('.message-computer p').css('font-size', v + 'em')
$('.message-user p').css('font-size', v + 'em')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" value="1" min="1" max="1.6" step=".1" id="slider" ondrag="changeSize()" />
How can I make the change in font size apply to all new elements sent to the browser?
Thanks
Not sure I understand well your problem, your code snippet doesn't contain any text.
But when using jQuery to update style, CSS statment is added individualy into each element style attribute (look at your browser inspector).
So newly added elements wont have their style attribute modified until you rechange the input value, and so will inherit from global CSS rules.
I suggest to apply the font style to the parents .message-computer & .message-user.
If you can't, wrap p elements into a dedicated div and apply the style to the div.
If you really need to apply it individually to each element, run $('input').trigger('change'); just after inserting new elements into the DOM.
What you want to do is add a class to a parent tag of your HTML, and to then have a CSS rule which applies to all of the like-elements on the page.
Then, no matter how many .message element you add to your .parent element, a CSS rule applies to them equally.
For instance, something like this would work. You could make this approach more efficient, but this illustrates the idea.
$('input').on('change', function() {
var v = $(this).val();
$('.parent').removeClass('font-1');
$('.parent').removeClass('font-2');
$('.parent').removeClass('font-3');
$('.parent').removeClass('font-4');
$('.parent').removeClass('font-5');
$('.parent').addClass('font-' + v);
});
.parent.font-1 .message {
font-size: 1em;
}
.parent.font-2 .message {
font-size: 2em;
}
.parent.font-3 .message {
font-size: 3em;
}
.parent.font-4 .message {
font-size: 4em;
}
.parent.font-5 .message {
font-size: 5em;
}
.message-computer {
color: red;
}
.message-user {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" value="1" min="1" max="5" step="1" id="slider" ondrag="changeSize()" />
<div class="parent font-1">
<div class="message-computer message"><p>I AM ROBOT</p></div>
<div class="message-user message"><p>Only human.</p></div>
</div>
You're only modifying existing node.
If you want that new node take those rules simply build a javascript function that add or update dynamically a css node
function changeSize(v)
{
var css = [
".message-computer p, .message-user p {font-size: "+v+"em;}"
].join("");
var head = document.head || document.getElementsByTagName('head')[0];
var style = null;
if(!document.getElementById("customTextSize"))
{
style = document.createElement('style');
style.id = "customTextSize";
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
else
{
style = document.getElementById("customTextSize");
style.removeChild(style.firstChild);
style.appendChild(document.createTextNode(css));
}
}
On your on change simply call the function :
changeSize(v)
I have a contenteditable tag, and I want my users to be able to type code into it. However, when I type into the contenteditable tag, my code shows up as text rather than an actual element. Is there a way for a user to create a full, working HTML element in a contenteditable box? I know it is possible for the client to insert code using javascript, but what about users who do not have access to javascript? How could users get code such as buttons inside a contenteditable box?
<p contenteditable="true">Try typing code in here as user, code will only be text...</p>
Is there a javascript way to accomplish this without JQUERY?
EDIT
I spent a long time searching for answers on Google, but nothing came up. The best solution I've gotten at this point has been #Dekel's comment on CKEditor. If there is another solution, I want to hear it. If there isn't, I'm sticking to CKEditor. I don't have much time, so I need a solution fast.
MORE EDIT =D
I recently developed my own answer to my question by looking at #Brandon's .replace answer (which only worked for client-coding, not user-coding) and modifying it to work with user-coding.
This isn't pretty, but you could make it work if you are looking to add HTML only. Otherwise an inline editor might work best.
var el = document.querySelector('p')
el.addEventListener('blur', function() {
var map = {amp: '&', lt: '<', gt: '>', quot: '"', '#039': "'"}
var html = this.innerHTML.replace(/&([^;]+);/g, (m, c) => map[c]);
this.innerHTML = html;
});
<p contenteditable="true">Try typing <b>code</b> in here as user, code will only be text...</p>
This answer is similar to #Brandon's idea, but is much more simple.
https://jsfiddle.net/azopqLe4/
<iframe width="100%" height="300" src="//jsfiddle.net/azopqLe4/embedded/js,html,result/dark/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
function convertit() {
var convet = document.getElementById("convet");
var text = convet.innerHTML;
var newtext;
newtext = text.replace(/</g, "<").replace(/>/g, ">");
convet.innerHTML = newtext;
}
//this version runs onrightclick =D
<p contenteditable="true" oncontextmenu="convertit();" id="convet">
Type some code here, then right-click... =D
</p>
In the second snippet, I typed <b>Test</b>, right-clicked it, and it became Test! My answer works through simple array replacement methods, although it is frustrating and time-wasting to keep right-clicking all the time. To prevent the actual contextmenu from popping up, just add .preventDefault().
You can't insert code, but you can insert DOMElements with JS. No need for jQuery.
var element=document.createElement("button");
element.innerHTML="Hello";
document.getElementById("yourContentEditable").append(element);
The idea with this would be to have a button to prompt for the code and insert it. Something like this:
(It is very ugly and buggy but it's just an example I just wrote)
var editorSelection=null;
function openCodePopup() {
//Store cursor position before editor loses focus
editorSelection=getEditorSelection();
//Open the popup
document.querySelector("#codePopup").style.display="block";
var ta=document.querySelector("#userCode");
ta.value="";
ta.focus();
}
function closeCodePopup() {
document.querySelector("#codePopup").style.display="none";
}
function insertCode() {
var code=document.querySelector("#userCode").value;
closeCodePopup();
if(code=="") return;
insertIntoEditor(html2dom(code));
}
function getEditorSelection() {
//TODO make crossbrowser
//TODO (VERY IMPORTANT) validate if selection is whitin the editor
var sel=window.getSelection();
if(sel.rangeCount) return sel.getRangeAt(0);
return null;
}
function insertIntoEditor(dom) {
if(editorSelection) {
editorSelection.deleteContents();
editorSelection.insertNode(dom);
} else {
//Insert at the end
document.querySelector("#editor").append(dom);
}
}
function html2dom(code) {
//A lazy way to convert html to DOMElements, you can use jQuery or any other
var foo=document.createElement('div'); //or you could use an inline element
foo.contentEditable=false;
foo.innerHTML=code;
return foo;
}
#editor {
height: 180px;
overflow: auto;
border: 1px solid #ccc;
}
#toolbar {
position: relative;
}
#codePopup {
position: absolute;
left: 10px;
top: 15px;
background-color: #fff;
border: 1px solid #ccc;
padding: 5px;
display: none;
}
#userCode {
display: block;
width: 200px;
height: 100px;
}
<div id="toolbar">
<button onclick="openCodePopup()"></></button>
<div id="codePopup">
<textarea id="userCode" placeholder="Type code here"></textarea>
<button onclick="insertCode()">Ok</button>
<button onclick="closeCodePopup()">Cancel</button>
</div>
</div>
<div contenteditable="true" id="editor"></div>
With the same idea you could create other options to convert element (example, text->link, etc.).
I have been scratching my head since yesterday on this problem, which I cannot solve. I am a new starter to Twitter Bootstrap and everything was going well until yesterday.
I am using the latest JQuery v1.11.1 and Twitter Bootstrap v3.3.1. Yesterday I downloaded Bootstrap Tags Input, from here: http://timschlechter.github.io/bootstrap-tagsinput/examples/
The plugin works and I have changed the CSS styles to match my page layout but the problem I am having is that the placeholder attribute will not disappear when on focus. If I type in a tag and add a comma value the placeholder will show until I start typing and then it will disappear again.
I have tried using JQuery onfocus function to remove the attribute when onfocus but it doesn't do anything. What I want to achieve is that when onfocus the placeholder does not show at that point not even on blur.
My input field is demonstrated below:
<input type="text" name="customer_tags" id="customer_tags" value="" placeholder="Enter you tags" data-role="tagsinput" required />
two years later, but i found how to work around this issue. First, if you inspect the DOM , you will see a new input text, which inherits our placeholder text, but without the extra function onblur, onfocus that everybody mention before.
<div class="bootstrap-tagsinput">
<input placeholder="text inherited from our input" size="23" type="text">
</div>
Then, to fix this issue, you had to create a jquery function to point that input. Like this:
$('.bootstrap-tagsinput input').blur(function(){jQuery(this).attr('placeholder', '')})
pointing to element with the class "bootstrap-tagsinput" and then the "input" objects inside. You can add a .focus function too if you prefered. In my case, works when the user leave the object and the input tags look clean without placeholder.
HTML5 placeholder attribute will not disappear when you focus in the input tag... it will only disappear when you start typing. It is the default behavior.
You can see it # W3Schools as well...
Following code works in my case:
<input type="text" name="add_image_tags" id="add_image_tags" data-role="tagsinput"
class="form-control" placeholder="Enter tags" data-placeholder="Enter tags" value="" />
handlePlaceHolder(); //Call during page load
function handlePlaceHolder()
{
if($('#add_image_tags').val())
{
$('.bootstrap-tagsinput input').attr('placeholder', '');
}
else
{
$('.bootstrap-tagsinput input').attr('placeholder',$('#add_image_tags').attr('data-placeholder'));
}
}
$('#add_image_tags').on('itemRemoved', function(event) {
// event.item: contains the item
handlePlaceHolder();
});
$('#add_image_tags').on('itemAdded', function(event) {
// event.item: contains the item
handlePlaceHolder();
});
Try this, i hope it's working:
<form>
<div>
<label for="name" class="left-label">Your Name</label>
<input type="text" class="example-two" placeholder="Enter you tags" id="name" name="name">
</div>
</form>
CSS:
[placeholder]:focus::-webkit-input-placeholder {
transition: opacity 0.5s 0.5s ease;
opacity: 0;
}
.example-two:focus::-webkit-input-placeholder {
transition: text-indent 0.5s 0.5s ease;
text-indent: -100%;
opacity: 1;
}
body {
}
form {
display: inline-block;
margin-top: 20px;
}
label {
display: block;
text-align: left;
font: bold 0.8em Sans-Serif;
text-transform: uppercase;
}
.left-label {
float: left;
padding: 8px 5px 0 0;
}
input[type=text] {
padding: 5px;
text-indent: 0;
}
form div {
margin: 20px;
clear: both;
text-align: left;
}
JSFiddle
EDIT:
Working on IE too:
JSFiddle
That's how the plugin behaves. As soon as you hit "enter" or "comma" it creates a span tag (see image attached)and shift the input to the right. So now the input has no value and should show the placeholder.
In their docs it's mentioned [Search for confirmKeys]
Array of keycodes which will add a tag when typing in the input.
(default: [13, 188], which are ENTER and comma)
Change the confirmkeys to remove creation of tags when you type comma
Edit:
On your site I tried the below method in console and it worked.
$('input').tagsinput({
confirmKeys: [13]
});
I was able to do a quick fix using jquery. The behavior I wanted should do two things:
1) Remove placeholder while on page after I've focused and started typing. So I will run it on keyup.
$(document).on('keyup', '.bootstrap-tagsinput input', function(){
$(this).attr('placeholder', '')
})
2) If there are already labels in an input, then I don't obviously need a placeholder. I run this on page load.
$('.labels').each(function(){
var len = $(this).tagsinput('items');
if(len){
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', '');
}
})
In my case, after a little modification, it works fine.
$('#txtTimeSlot').on('change', function () {
var len = $(this).tagsinput('items').length;
if (len > 0) {
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', '');
} else {
var $input = $($(this).prev().children('input').get(0));
$input.attr('placeholder', $(this).attr('placeholder'));
}
});
for all who are still having this problem, just change the line in the javascript file:
from:
cancelConfirmKeysOnEmpty: true,
to
cancelConfirmKeysOnEmpty: false,
And thats all!
I am trying to make a textarea that only will type in caps, even if the user isn't holding down shift or has caps lock on. Ideally this would accept the input no matter what and just automatically shift it to all caps. Most of the ways I am thinking of seem kind of clunky and would also show the lowercase before it gets converted.
Any suggestions or strategies?
you can use CSS
textarea { text-transform: uppercase; }
however, this only renders on the browser. let's say if you want to inject the text into a script or db in the textarea as all caps then you'll have to use javascript's toUpperCase(); before injection or form submit.
here is the jsfiddle for example:
html:
<textarea>I really like jAvaScript</textarea>
css:
textarea{
text-transform: uppercase;
}
javascript:
var myTextArea = document.getElementsByTagName('textarea');
for(var i=0; i<myTextArea.length; i++){
console.log('Textarea ' + i + ' output: ' + myTextArea[i].innerHTML); //I really like jAvaScript
console.log('Textarea ' + i + ' converted output: ' + myTextArea[i].innerHTML.toUpperCase()); //I REALLY LIKE JAVASCRIPT
}
CSS:
textarea { text-transform: uppercase; }
Quintin,
Create a style in your CSS such as the following:
textarea{
text-transform:uppercase;
}
Try adding a
textarea{
text-transform: uppercase;
}
to the text area.
Add you can get it
CSS:
textarea { text-transform: uppercase; }
This can be achieved with the oninput attribute, like so:
<textarea oninput="this.value = this.value.toUpperCase()">
<label for="upperCaseTextArea" style="display:block;">
Upper Case Text Area
</label>
<textarea
id="upperCaseTextArea"
name="upperCaseText"
rows="5"
cols="15"
oninput="this.value=this.value.toUpperCase()"
>
</textarea>