Stop changing cursor location when innerHTML is changed - javascript

How do I stop the cursor changing location when innerHTML is edited by javascript?
I am currently making a little code editor project where I want text highlighting, but to do that I must edit the innerHTML / DOM element to add a span into it. But when that happens it changes location to start of text.
var c = document.getElementById("c");
var t = setInterval(function(){
c.innerHTML = $("#c").text().split("lol").join("<span class='hi1'>lol</span>");
},1);
[contenteditable] {
border: 1px solid gray;
}
.hi1 {
color: rgb(51, 153, 255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable id="c">
write "l o l" without spaces. Then continue to write and try to change location with arrow keys / mouse
</div>

Related

Why can I not add a space to the text of a HTML button with the 'contenteditable' attribute?

I have a button in HTML and I want the user to be able to change the button's text when double clicking.
<button onclick='doStuff()' ondblclick='renameButton()' id='myButton'>Click Me</button>
This is my function in JavaScript:
function renameButton() {
var button = document.getElementById('myButton');
button.setAttribute("contenteditable", true);
}//end renameButton
This function allows me to edit the button:
Issue 1) I cannot add a space when editing the button. The space-bar on my keyboard literally does nothing.
Issue 2) Is it possible to set a white background on the editable text to allow the user to see that it is editable? As far as I know, it is only possible to control the background color of the entire button element, but not the text node.
You need to put a span kind of element to hold the text inside the button if you want to make sure SPACE is fed into the content.
On a button, space is a trigger for button press and hence can't be added in to the text with contenteditable attribute.
See it working here: https://jsfiddle.net/mwwj1jty/2/
HTML
<button onclick='doStuff()' ondblclick='renameButton()' id='myButton'><span id="myspan">Click Me</span></button>
JAVASCRIPT
function renameButton() {
var span = document.getElementById('myspan');
span.setAttribute("contenteditable", true);
span.style.backgroundColor = "red";
}//end renameButton
You could put a span inside the button where the text is, and change the background-color of the span instead as seen here https://jsfiddle.net/msoLg3qb/
HTML
<button ondblclick='renameButton()' id='myButton'><span>Click Me</span></button>
CSS
span {
background-color: white;
}
button {
background-color: green;
}
JAVASCRIPT
var button = document.getElementById('myButton');
function renameButton() {
button.setAttribute("contenteditable", true);
}
Don't use a button element for this, as you can see that there are limitations. When a button is active, pressing the SPACE key initiates a click event. To get around this, use a different element, a span would be perfect here.
I've also added the background color as you asked about.
Lastly, don't use inline HTML event attributes (onclick, etc.). That's an ancient technique that just will not die but has many reasons not to use it. Instead, follow modern standards and use .addEventListener().
// Get a reference to the button
var spn = document.getElementById("myButton");
// Set up your event handlers in JavaScript, not in HTML
spn.addEventListener("click", doStuff);
spn.addEventListener("dblclick", renameButton);
spn.addEventListener("blur", saveName);
function renameButton() {
spn.contentEditable = "true";
spn.classList.add("edit");
}
function saveName(){
spn.contentEditable = "false";
spn.classList.remove("edit");
}
function doStuff(){
}
/* Make span look like a button */
.button {
display:inline-block;
padding:5px 20px;
border:1px solid grey;
background-color:green;
border-radius:2px;
cursor:pointer;
box-shadow:1px 1px 1px grey;
color:white;
user-select:none;
}
/* Make span feel like a button */
.button:active {
box-shadow:-1px -1px 1px white;
}
/* Style to add while content is editible */
.edit {
background-color:white;
color:black;
}
<span id='myButton' class="button">Click Me</span>

IF DIV color is red? [duplicate]

This question already has answers here:
How to compare colors in JavaScript?
(6 answers)
Closed 5 years ago.
I have made a DIV that changes color, but I'm trying to find a way to know when it turns red. Here's what I need it to do:
if (DIV BACKGROUND COLOR RED) {
alert("DIV IS RED");
}
How would I accomplish this?
Yes can do this by using attribute change jquery plugin...
As I can see you want an event to be triggered on color change automatically... So, your code will be something like this with its working example...
$("#myDiv").attrchange({
trackValues: true,
// set to true so that the event object is updated with old & new values
callback: function(evnt) {
if(evnt.newValue.indexOf('background: red') > -1) {
// which attribute you want to watch for changes
alert("DIV IS RED");
}
}
});
function change(x){
document.getElementById("myDiv").style.background=x;
}
#myDiv{
background:green;
}
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
<script src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange_ext.js"></script>
<div id="myDiv">This Div Changes colors</div>
<button onclick="change('red');">Change To Red</button>
<button onclick="change('blue');">Change To Blue</button>
<button onclick="change('green');">Change To Green</button>
The above code will prompt a message when the div turns red...
You can access an element's background colour via window.getComputedStyle(element).backgroundColor.
This will be a string in either "rgb" or "rgba" representation, e.g.:
rgb(127, 127, 127)
rgba(127, 127, 127, 1)
An element is "red" if it's red component (the 1st number) is greater than the other colour components. Both rgb and rgba have 3 color components, and rgba has an extra "alpha" (transparency) component - which we can ignore, because it doesn't affect "redness".
We'll get the red green and blue components of the element's background color, and consider the element "red" if its red color component is greater than the green and blue components:
var isRed = function(element) {
var bg = window.getComputedStyle(element).backgroundColor;
if (!bg) return false; // Sometimes there is no background color, in which case the element isn't red
// Otherwise, `bg` is a string:
var rb = bg.indexOf('(');
bg = bg.substr(rb + 1); // Trim off everything up until and including the "(" character
bg = bg.split(','); // Split on the "," delimiter
var r = parseInt(bg[0].trim());
var g = parseInt(bg[1].trim());
var b = parseInt(bg[2].trim());
return r > g && r > b;
};
console.log('#red?', isRed(document.getElementById('red')));
console.log('#green?', isRed(document.getElementById('green')));
console.log('#blue?', isRed(document.getElementById('blue')));
console.log('#quiteRed?', isRed(document.getElementById('quiteRed')));
console.log('#notRed?', isRed(document.getElementById('notRed')));
console.log('#transparentRed?', isRed(document.getElementById('transparentRed')));
.col {
width: 100%;
height: 30px;
color: #ffffff;
line-height: 30px;
}
#red { background-color: #ff0000; }
#green { background-color: #00ff00; }
#blue { background-color: #0000ff; }
#quiteRed { background-color: rgb(220, 130, 120); }
#notRed { background-color: #80b0c0; }
#transparentRed { background-color: rgba(200, 50, 50, 0.4); }
<div class="col" id="red">red</div>
<div class="col" id="green">green</div>
<div class="col" id="blue">blue</div>
<div class="col" id="quiteRed">quiteRed</div>
<div class="col" id="notRed">notRed</div>
<div class="col" id="transparentRed">transparentRed</div>

Edit, drag and drop boxes on webpage and save contents and position

I am looking for a starting point as to how to achieve a simple webpage with drag and drop boxes. The boxes should be editable (either text content or some html/image upload functionality).
Any visitor to the site should be able to move boxes around, change the contents and then save the results (or ideally they don't even need to click a save button).
Where should I be starting to achieve this? The hardest part I envisage is how to 'save' to the server and then serve the edited version of the page? I don't know how to use SQL, and have limited knowledge of server side script.
I am not looking for a full solution here, just some pointers please!
Thank you.
I am just providing you the template to start with.
Below code will allow you to move div and also edit text.
var makeMove;
x0=0;
y0=0;
function move(e){
if(makeMove){
x1 = e.clientX;
y1 = e.clientY;
cx=x0+x1-x;
cy=y0+y1-y;
document.getElementById("dragableForm").style.left = cx +"px";
document.getElementById("dragableForm").style.top = cy +"px";
e.preventDefault();
}
}
function mouseUp(e){
makeMove=false;
x0=cx;
y0=cy;
}
function mouseDown(e){
makeMove=true;
x = e.clientX;
y = e.clientY;
}
.container{
width: 600px;
height: 500px;
border: 1px solid black;
overflow: hidden;
}
#dragableForm{
border:1px solid black;
position:relative;
}
<body>
<div class="container" onmousemove="move(event)" onmouseup="mouseUp(event)" onmousedown="mouseDown(event)">
<div id="dragableForm" style="background-color: #00ff00;padding:10px;width:70%">
<textarea rows="4" cols="50">
your input here
</textarea>
<button>save</button>
</div>
</div>
</body>

jquery mobile phonegap fillText max width property not working

i am working on an app that types text on to the image..so i dont want the text to go out of the image.
here is my code:
style
#container{
overflow: hidden;
z-index: 0;
}
#myCanvas{
z-index: 1000;
border: 2px solid red;
width: 100%;
}
html code
<div id="container">
<canvas id="myCanvas"></canvas>
</div>
script
$(document).ready(function(){
var context2= $("#myCanvas")[0].getContext('2d');
$("#myCanvas,#container").height((3*window.innerWidth)/4);
context2.fillStyle = "#0000ff";
context2.fillRect(0,0,context2.canvas.width,context2.canvas.height);
$("#toptext").on("keyup",function(){
//save blue style of fill rectangle
context2.save();
var topTxt=$(this).val();
//clear the rectangle
context2.clearRect (0,0,context2.canvas.width,context2.canvas.height);
//draw the canvas again to get fresh frame
context2.fillRect(0,0,context2.canvas.width,context2.canvas.height);
//change fill style to white
context2.fillStyle = "#ffffff";
var maxWidth=50;
context2.font="bold 25px verdana";
context2.fillText(topTxt,50,50,100,100,**maxWidth**);
//
context2.restore();
});
});
notice max width is set. so the text should not go out of the width provided
It works fine in the browser but as soon as u convert it to a phonegap app the width is no longer applied and text goes out out the image:
see the app here:
https://build.phonegap.com/apps/1171739/download/android/?qr_key=JrAyvaQENkAkowwmdDjC
here is my git:
https://github.com/prantikv/image-typer/tree/gitless
i have checked it after removing jquery mobile and i have the same issue...so the problem is either with android or phoneGAP...
How to get around it
I think you are using the fillText wrong because it is defined as follows:
void fillText(
in DOMString textToDraw,
in float x,
in float y,
[optional] in float maxWidth
);
and you are calling it with: context2.fillText(topTxt,50/*x*/,50/*y*/,100/*max-width*/,100,**maxWidth**);
So the last two aren't actually used.
See definition here: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text#fillText()

If textbox contain a specific string do some function - javascript

I am wondering how to search specific string in big textbox (which contains 200 words) so I can make function to color them. Ex. In textbox there is a sentence "my dog is happy" and i want string "dog" to become red by button or sth else. Is it possible???
Yes, it is possible. But don't use a text box or text area, use a div with contenteditable = "true":
<div id="editableDiv" class="editable" contenteditable="true">
This is a sentence containing 'dog'.<br />
You can edit the contents of this div.
</div>
<button id="highlightBtn">Highlight "dog"</button>
<script type="text/javascript">
highlightBtn.onclick = function() {
var elem = document.getElementById('editableDiv');
elem.innerHTML = elem.innerHTML.replace(/dog/g,
'<span class="redText">dog</span>');
}
</script>
And don't forget to create the classes redText and editable in your stylesheet:
.editable {
padding: 5px;
border: dashed 1px black;
}
.redText {
color: red;
}
JSFiddle: http://jsfiddle.net/ProgramFOX/UMMPh/

Categories

Resources