Display LIVE Preview Of Textarea Front End Javascript - javascript

On my project I have a div which is a text area where I can wrap text in to code format.
I also have a button with a id="preview"
Is it possible in another div to display the output of the text area once click on preview button in a front end view like what it would be like on IE or FIREFOX.
Codepen Example: http://codepen.io/riwakawebsitedesigns/pen/lfpKF
HMTL Code
<div class="container">
<textarea id="widget">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus repellendus inventore, voluptatum ipsa ipsum debitis voluptates, laudantium nulla odio sed, pariatur quaerat quae numquam beatae ad odit optio quasi magni explicabo tenetur. Consectetur, animi, autem? Non laboriosam ad nisi, commodi, dolores soluta. Dolorum error unde itaque ipsum a? Libero sapiente eligendi similique, itaque deserunt aliquid magnam ducimus nesciunt, iste ad nihil labore assumenda soluta earum. Rerum deserunt totam aperiam maiores facere eum sapiente modi non debitis consectetur voluptatum, voluptatibus labore repellendus tempora voluptate error nesciunt eaque possimus. Consectetur laborum ab ipsum, voluptate perspiciatis quos omnis delectus dicta mollitia atque voluptates!</textarea>
<div class="buttons">
<button id="code">Code</button>
<button id="preview">Preview</button>
</div>
<!-- Should display live out put of wraped code.-->
<div id="preview" class="code-preview"></div>
</div>
Javascript
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$('#bold').click(function() {
wrapText("widget", "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("widget", "<em>", "</em>");
});
$('#underline').click(function() {
wrapText("widget", "<u>", "</u>");
});
$('#code').click(function() {
wrapText("widget", "<pre><code>", "</code></pre>");
});

Change your ID of preview button, like this:
<button id="preview-btn">Preview</button>
And in your JS:
$('#preview-btn').on('click', function () {
$('#preview').html($('#widget').val());
});
CodePen Demo

Related

Iterating with Each Quiz Jquery

$('p').each(function (index) {
var letters = $(this).text().length;
$('p').appendTo('<span> Here is ' + letters + '</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>
Hello There , I will appreciate a lot any help with my code , I need to count all letters per one <p> Tags and show it on the end of <p> tag but my code count all of <p> tags which I have on the page and put it together in every of them , can any body give me advise what is . wrong and how to fix it , Thank you so much
Because $('p') will find every <p> in page the same way you are using it to set up the initial query
You want the specific instance inside the each which is $(this) and you want append() not appendTo()
$('p').each(function (index) {
var letters = $(this).text().length;
$(this).append('<span style="color:red"> Here is ' + letters + '</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>
$('p').each(function (index) {
$('<span></span>',{text : " Here is " + $(this).text().length + ""}).css({color:'blue'}).appendTo(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet vel fugit repellendus, magni blanditiis delectus autem dicta, omnis odit beatae iusto asperiores, iste. Delectus, eaque reiciendis quibusdam cupiditate molestias officia perspiciatis corporis cumque saepe voluptatem, magnam magni asperiores a!</p>

Add spellcheck to non-contenteditable div?

Is it possible to run the browser's in built spell checker on divs which aren't contenteditable? The below code works for checking spelling, but the div must be contenteditable and the spell check is only executed once the div is put into focus.
<div contenteditable="true" spellcheck="true">
This paragraph gets spell checked when the div comes into focus
</div>
I want to display a full page of html and have the red squiggly lines underneath all the mis spelled words
Let me say, these steps might work:
Make all the <div> to be focussable by adding a tabindex attribute.
Once focussed, using jQuery (as it is not possible using CSS), add contenteditable attribute.
Once blurred, remove the contenteditable attribute.
Snippet
$(function () {
$(".ce").focus(function () {
$(this).prop("contenteditable", true);
}).blur(function () {
$(this).prop("contenteditable", false);
});
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<input type="text" placeholder="Click here and press tab!" />
<div class="ce" tabindex="0">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis dolorem consequatur doloribus at, quam ipsam repudiandae libero ullam, commodi cum hic nam odit reiciendis? Distinctio inventore quasi, ex cupiditate neque.</div>
<div class="ce" tabindex="0">Sunt, consequatur. Dolorem odio nihil minima, in autem corrupti. Animi atque, eius laudantium. Excepturi laudantium suscipit esse nulla tempore aspernatur architecto. Dolorem a impedit, dolor voluptatum repellat mollitia itaque quod.</div>
<div class="ce" tabindex="0">Aliquam dolores, ipsam vel eum sed necessitatibus itaque error doloribus illum, omnis, ex exercitationem commodi neque quos voluptatibus debitis rem amet praesentium! Quibusdam corporis mollitia modi? In dignissimos ad itaque.</div>
<div class="ce" tabindex="0">Maxime, totam laudantium accusantium itaque sint possimus ex minus deleniti adipisci reprehenderit commodi illo corporis provident sed tempore architecto molestiae! Molestiae voluptas magni, non, ex assumenda quibusdam aliquam vitae ab.</div>
<div class="ce" tabindex="0">Quibusdam magnam, maiores eveniet commodi consequuntur sapiente, deleniti praesentium eius blanditiis. Suscipit fugit in repellendus quis ducimus illum, tempore voluptatem incidunt recusandae a perferendis id, distinctio vitae voluptatibus quibusdam necessitatibus.</div>
I used the following code to apply the spell checker using jquery-2.2.1.js. I made all divs contenteditable and then after view loaded ran:
$('.content-container').each((i, el: any) => {
$(el)[0].focus();
$(el)[0].setAttribute('contenteditable', 'false');
})

Remove class if clicked outside an element

How do I make it so that if I click outside a paragraph element then the background color is removed? Note I want to it to only be able to highlight one p at a time.
$('p').click(function() {
$('p').removeClass('yellow');
$(this).addClass('yellow');
});
.yellow {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit tenetur sequi amet sit dolorem, nulla inventore quo cum ad distinctio aut nesciunt reprehenderit dolorum quidem animi unde aspernatur. Esse, eius!</p>
<p>Deleniti vitae rerum eum saepe eaque tenetur libero, omnis nisi sapiente dicta est repellat, provident placeat quia inventore, at architecto quisquam, pariatur minus quam magni totam praesentium dignissimos. Incidunt, sequi.</p>
<p>Fuga cupiditate consectetur, corporis architecto, doloremque impedit ullam quia praesentium voluptatibus molestiae dolor sint, odio amet atque culpa fugit blanditiis ea nam repellat necessitatibus. Aliquam voluptate fuga quo, omnis mollitia.</p>
</div>
</div>
</div>
Here is what you want:
$('p').click(function(e) {
$('p').removeClass('yellow'); //If there is any p with class yellow, it removes that
$(e.target).closest('p').addClass('yellow'); //This find closest target when you click, in our case current paragraph(p)
});
$(document).click(function(e){ //Here is when you click in your entire document
if($(e.target).closest('p').length==0) { // If click is not paragraph
$('p').removeClass('yellow'); //It removes this class existed from any paragraph
}
})
.yellow {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit tenetur sequi amet sit dolorem, nulla inventore quo cum ad distinctio aut nesciunt reprehenderit dolorum quidem animi unde aspernatur. Esse, eius!</p>
<p>Deleniti vitae rerum eum saepe eaque tenetur libero, omnis nisi sapiente dicta est repellat, provident placeat quia inventore, at architecto quisquam, pariatur minus quam magni totam praesentium dignissimos. Incidunt, sequi.</p>
<p>Fuga cupiditate consectetur, corporis architecto, doloremque impedit ullam quia praesentium voluptatibus molestiae dolor sint, odio amet atque culpa fugit blanditiis ea nam repellat necessitatibus. Aliquam voluptate fuga quo, omnis mollitia.</p></div>
</div>
</div>
Use this code
$("p").click(function (e){
$("p").removeClass("yellow");
$(this).addClass("yellow");
});
$(document).click(function (e){
var element = $("p.yellow");
if (!element.is(e.target) && element.has(e.target).length === 0)
element.removeClass("yellow");
});
.yellow {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="yellow">Text text text</p>
<p>Text text text</p>
<p>Text text text</p>
You can set a listener to the <body> and check if the click was onto a <p>:
$('body').click(function(event) {
if(!$(event.target).is('p')) {
$('p').removeClass('yellow');
}
else {
$(event.target).addClass('yellow');
}
});

JavaScript: get scrollY position of searched text on body [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need scrollY position of searched text. How to find text in body and get scrollY position of the found text.
Following code is an example about question:
(all is clear)
<script>
function getScrollYPosition(var str){
/* step 1: search str in <body> and found.
* step 2: get scrollY position of found str.
* step 3: return position. (500)
*/
}
</script>
<body>
<p>Hello world</p> /*For example scrollY position is 500*/
<p>...</p>
<p>...</p>
</body>
You could first match the text string,
wrap it into an (span) element
and than calculate that element offset position
Here's a quick example
var word = 'dolor';
var rgx = new RegExp('\\b('+word+')\\b', 'ig');
// CREATE SPAN ELEMENTS WHAT WILL WRAP THE QUERY STRING (WORD)
$('div, div *').contents().filter(function() {
return this.nodeType === 3;
}).each(function() {
$(this).replaceWith($(this).text().replace(rgx, "<span class='match'>$1</span>"));
});
// COLLECT ALL SPAN POSITIONS
var positions = $('.match').map(function(){
return this.getBoundingClientRect().top;
}).get();
alert(positions);
div{font-size:50px;}
span.match{background: gold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut voluptatum, provident saepe. Culpa animi sint, itaque iure error hic qui blanditiis perspiciatis adipisci, libero quia veritatis dignissimos quasi id cumque!</div>
<div>Magni cupiditate laudantium, corrupti commodi, reiciendis consequuntur recusandae minima tempore id placeat rerum saepe molestiae, nulla illo, dolores distinctio aliquid asperiores esse maxime voluptatibus corporis at. Commodi eius magni esse!</div>
<div>Maiores explicabo, dolor nemo mollitia cumque et nobis quae consectetur alias dicta quod facere saepe aspernatur sint ex soluta nulla veritatis ab. Sunt aspernatur distinctio quam alias quis possimus reiciendis impedit.</div>
<div>Est sequi eius nam, odio ut commodi quam omnis aperiam, vel, sunt quaerat adipisci voluptates natus possimus consequuntur corporis atque facere corrupti, rem autem modi ipsam inventore nobis! Itaque, modi?</div>
<div>Velit, cumque in dicta ratione iste autem, atque dolor magni optio, excepturi qui ipsam laboriosam modi quidem cupiditate sapiente perferendis! Iste eos fuga ut eum deserunt repellendus ex qui, illo eaque!</div>
<div>Ullam a, labore aperiam ex culpa nesciunt ipsam voluptatibus maiores consequatur qui repellendus obcaecati tenetur, consectetur eos, ut voluptate, nemo placeat soluta odit? Error, Dolor, voluptatibus! Id sed alias et consectetur.</div>
<div>Ipsa pariatur tenetur, nobis recusandae deserunt quisquam nesciunt, ex consequuntur minus voluptatem dolores officiis itaque fuga reiciendis dolor praesentium quae maxime repudiandae. Quibusdam sint fugit soluta pariatur, alias, eveniet natus culpa!</div>
You could be a little more specific with your answer. If I understand correctly you need to find an element that contains a given text and get its vertical offset. You could try the following:
$($(":contains(YOUR_TEXT)").slice(-1)[0]).offset().top

Randomly selecting a paragraph from Array list Javascript

I am working on my own Lorem Ipsum generator, with the added bonus of generating the corresponding HTML formatting code in a box beside it.
So, the paragraph is generated via this button
<button id="generate" type="button" onclick="LoremIpsumRandom()">1 Paragraph</button>
and is generated here
<p id="textarea"></p>
function LoremIpsumRandom()
{
//global to store previous random int
_oldInt = null;
var pickRandom = function(paragraphArray)
{
//random index of paragraphArray
var randomInt = Math.floor(Math.random()*paragraphArray.length);
//ensure random integer isn't the same as last
if(randomInt == _oldInt)
pickRandom(paragraphArray);
else{
_oldInt = randomInt;
return paragraphArray[randomInt];
}
}
//your lorem ipsum paragraphs
var paragraphArray = [
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.",
"Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.",
"Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?", "Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.",
"Et harum quidem rerum facilis est et expedita distinctio.", "Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.",
"Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.",
"Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
];
//update element content (e.g. `<div>` with paragraph
document.getElementById("textarea").innerHTML = pickRandom(paragraphArray);
//document.getElementById("textarea-code").innerText = pickRandom("<P>" + (paragraphArray) + "</P>");
}
No point including the CSS to be honest - it's just standard text boxes and auto-generated buttons.
So, the issue is that although I can generate the normal paragraph in the id="textarea" section, I want to be able to generate a raw HTML version as well (with the paragraph and line breaks code being shown.) So far, I've been able to generate the raw HTML with no issues, but when I added #pixelbobby 's section (which makes sure that when a sentence is selected, the next selection won't be the same, as true randomness can sometimes generate), the code doesn't work. In some instances, it's generated the raw HTML, but the generated paragraph is a different one.
The other functions (generating lists, multi-paragraphed sections and multi-levelled lists) utilise the raw HTML and output correctly, and it all runs smoothly. The raw HTML is always outputted to
<p id="textarea-code"></p>
which is next to the first textarea section.
Can someone tell me how I can modify the script so that the raw HTML part of the script generates the same paragraph as the result of the pickRandom(paragraphArray)
So,
This - document.getElementById("textarea-code").innerText = pickRandom("<P>" + (paragraphArray) + "</P>");
needs to be the same as - document.getElementById("textarea").innerHTML = pickRandom(paragraphArray);
but with the raw HTML specified in the pickRandom() part of the line.
Can anyone help?
Thanks :)
You can save the result of pickRandom(paragraphArray) in a variable and use it twice:
var randomParagraph = pickRandom(paragraphArray); //save the result of pickRandom
document.getElementById("textarea").innerHTML = randomParagraph;
document.getElementById("textarea-code").innerText = "<P>" + randomParagraph + "</P>");

Categories