Append text to currently selected div - javascript

I'm working on this website www.betamaths.eu
When a user had clicked inside one of the divs that have placeholder text and then click a button on the left, I would like the text from that button to append inside the div.
I have this code from another user which appends or prepends text ouside the div (not what I am looking for. You can test it with the lowercase alpha button in the menu on the left of the webpage listed above if you wish to get a better understanding.
<script type="text/javascript">
var No = 0;
var focusedElement;
$(document).ready(function() {
$('#answer_step1').on('click','div',function() {
focusedElement = this;
});
$('#alpha').on('click',function() {
$('#answer_step1').prepend('<div>Test'+No+'</div>');
No++
});
});
If I change the line
$('#answer_step1').append('<div>Test'+No+'</div>');
to
$('#answer_step1').append('Test'+No);
nothing happens. Any help is appreciated. If I can get one of these working, the rest will be easy.

You must have a syntatically error in your code, because I used your same code and was able to accomplish the append();
HTML:
<button id="alpha">
Click
</button>
<div id="answer_step1">
hi
</div>
Javascript:
var No = 0;
var focusedElement;
$(document).ready(function() {
$('#answer_step1').on('click','div',function() {
focusedElement = this;
});
$('#alpha').on('click',function() {
$('#answer_step1').prepend('Test' + No);
No++
});
});
https://jsfiddle.net/typtzr7z/

Related

Content Editable Div, appending HTML causing issue. Every text typed after programatically appending HTML gets added to the last HTML tag

I am trying to make a content editable div that can be used to generate message templates for an app. Users can append placeholders for fields like names to a template by hitting a button. The placeholders can be removed by hitting an 'x' on them as well. Here's the working snippet.
var removePlaceholder = function(e){
e.parentNode.parentNode.removeChild(e.parentNode);
}
var appendPlaceHolder = function(field){
var e = document.getElementById("t");
e.innerHTML += ('<span class="tag">{'+field+'}<span onclick=removePlaceholder(this) class="remove">x</span></span>')
}
.tag {
background-color : blue;
color : white;
}
.remove {
color : red
}
<div id="t" contenteditable="true">Hello</div>
<button onclick=appendPlaceHolder("first_name")>Add first name</button>
The contenteditable part works just fine. But after I've added a placeholder using my appendPlaceHolder function, everything I type seem to get appended to the last inserted HTML element.
How can I prevent this. I have closed the tag properly. Is there any way to change this behaviour.
To recreate issue, run the snippet and hit the "Add First Name" Button, then continue typing in the area.
Update
Have added image to explain the situation
What you can do is add a space after the placeholder has been appended:
JavaScript
var removePlaceholder = function(e){
e.parentNode.parentNode.removeChild(e.parentNode);
}
var appendPlaceHolder = function(field){
var e = document.getElementById("t");
e.innerHTML += ('<span class="tag">{'+field+'}<span onclick=removePlaceholder(this) class="remove">x</span></span> ')
}
Note: The which has been added at the end of the span just creates a space.
Live Example
JSFiddle

Nesting DIV using JavaScript

I am trying to load DIV on button click inside another DIV and on another click it should create a new DIV inside the newly created DIV. Here is my fiddle:http://jsfiddle.net/LzCW5/4/ and my code:
HTML:
Generate
<div id='x0'>
0
</div>
JavaScript:
int level=1;
function nestDiv()
{
document.getElementById('x'+(level-1)).innerHTML="<div id='x"+level+"'>"+level+"</div>";
level++;
if(level==5)
//do somthing
}
I also want to perform some special operation when nesting level reaches 5. I am not so pro at JavaScript. So please tell me how can I achieve this?
In your code you only have to change int to var and call the function as a variable:
var level=1;
nestDiv = function()
{
document.getElementById('x'+(level-1)).innerHTML="<div id='x"+level+"'>"+level+"</div>";
level++;
}
You can see this working here
Here's how to append a div in jQuery:
var newDiv = $("<div id='x"+level+"'>"+level+"</div>");
$('#x'+(level-1)).append(newDiv);
This should replace your document.getElementById... line
My understanding as per your question:
When you click a button, add a div to another div.
Now when the user clicks another button, new div must be added in the previously created new div.
so let's break it down:
$("button").click(function() {
if($("#referenceDivId").children().length == 0) {
// if there are no children initially
$("#referenceDivId").append("<div>New div</div>");
} else if($("#referenceDivId").children().length == 5) {
// do your magic when children divs are 5
}
else {
// if it already had children
$("#referenceDivId").find("div:last").append("<div>New div</div>");
}
});
DEMO

jQuery++, problems on .selection()

everybody.
I have a little problem; I'm trying to build a WYSIWYG, but I encountered some problems.
I have a contenteditable div with id = desc2, and some buttons. Let's take, for example, the button "bold".
<div class="magic" magic_id="desc2">
<div class="magicbutton one" magic="[b]%s[/b]">
<span style="font-weight:bold;">Bold</span>
</div>
</div>
And I have some jQuery++ selection application in:
$('#desc2').on('mouseup', function() {
var selection = $(this).selection(),
text = $(this).text().substring(selection.start, selection.end);
console.log(text);
});
I have erased the other part of the script, because if I manage to get this to work, I'm done :D
So, as I was saying, if I do this, everything is good: I sleect a part on the div and on the console is outputted the content.
But this is not what I want to do. I wrote this:
$('.magicbutton.uno').on('click', function(){
var id = $(this).parent().attr("magic_id");
var selection = $("#"+id).selection(),
text = $("#"+id).text().substring(selection.start, selection.end);
console.log(text);
});
Everytime I click, it takes the ID of the div to change and should output the selected text, but it doesn't.
The code is the same, and i checked that $(this) in the first script is the same as $("#"+id) in the second.
What can I do? Thanks!
EDIT: jsFiddle
When DIV loses focus, selection is nullified. As a workaround, you could use data object:
DEMO
$('.magicbutton.one').on('click', function(){
var id = $(this).parent().attr("magic_id"); //id = desc2, i used this because i could have multiple forms in a page
var selection = $("#"+id).data('selection');
alert(selection);
}); //This doesn't work
$('#desc2').on('mouseup', function() {
var selection = $(this).selection(),
text = $(this).text().substring(selection.start, selection.end);
$(this).data('selection', text);
});

Jquery get readout of text area live

I was wondering if I could get a little help. I want to get a live preview of what is in my text area above it.
Each new line in the text area will display as a list above it, so something like this:
test
test2
test3
Text area:
test
test2
test3
How I want it to work is that on load it reads the contents of the text area and displays the contents above in a list. Then when the contents of the text area changes it also changes the list above it.
Here is my code: http://jsfiddle.net/spadez/9sX6X/
<h4>Placeholder</h4>
<ul id="tst"></ul>
<textarea rows="4" cols="50" placeholder="Test" id="test"></textarea>
This is how far I got:
$('#test').bind('input propertychange', function() {
if(this.value.length){
Rerender list to show contents
}
});
This is one of my first scripts so could someone please give me some guidance on how this should be achieved?
Fiddle
var list = $('#tst');
$('#test').on('keyup', function() {
list.empty();
if(this.value.length){
$.each(this.value.split("\n"), function(i, val){
list.append($('<li></li>').text(val));
});
}
});
$('#test').trigger('keyup'); // required to make it do the update onload
Because of my usage of .text(), this will handle special characters such as < and > without a problem. Also note how I have only selected the <ul> a single time, instead of re-selecting it over and over.
Side note: as of jQuery 1.7, .on() is preferred instead of .bind().
is this what you are looking for? http://jsfiddle.net/9sX6X/2/
CODE
$('#test').bind('keyup', function () {
if (this.value.length) {
var inp = this.value.split("\n");
$("#list").empty();
for(var x = 0; x < inp.length; x++){
$("#list").append("<li>"+inp[x]+"</li>")
}
}
});
Hope it helps
You could do this:
$('#test').on('change', function () {
var lines = $(this).val().split('\n');
$('#tst').empty();
for (var i = 0;i < lines.length;i++){
$('#tst').append('<li>' + lines[i] + '</li>');
}
});
Note: this code works on the change event of the textarea, thus you need to click outside of the textarea for the event to fire. If you want to do it on every key press, you should change the event from change to keyup. However, this does lead to far less performance.
You can see the updated fiddle here: http://jsfiddle.net/xv73p/

changing input text to textarea just like in facebook

i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}

Categories

Resources