Javascript, writing dynamic content to textarea - javascript

I am programming a blog in php, for the record I've just started out but Im doing pretty good with this PHP but Javascript I don't really understand.
On my blog I would like people to comment and discuss.
What I want:
Every comment has an id that is displayed.
I want to click on it and then the Javascript should place it in the textarea for leaving comments.
Thats all.

(This answer uses jQuery.)
// getting a reference to the TEXTAREA element
var $ta = $("#new_comment textarea");
$(".comment").click(function() {
var text = $(this).find(".text").text(); // depends of the structure
$ta.val(text);
});
<div class="comment">
<p class="author"> Peter </p>
<p class="text"> Good article! </p>
</div>

Related

html Multilingual website - Language latency occurring

I'm implementing a multilingual solution on my website : I detect the browser language of the user.
What I have in the HTML is the default text in English.
All the text objects are being assigned an id.
Then in a JS sheet I use innerHTML to replace the text in the correct language, to translate into French.
HTML
<div>
<h3 id="test">
This is a Test !
</h3>
</div>
JS
function adjust_languages() {
// change all object text, if french
if (sprache == "french") {
document.getElementById("test").innerHTML = "Ceci est un test !";
}
This works quite well. However, when the user's connection is not very fast, a latency occurs between the moment when the HTML text is displayed in English and the moment when it gets translated into French.
In other words, the user sees English for let's say 1 second, before it gets translated into French.
I was thinking of getting rid completely of text in the HTML and have the English language in the JS as well, but that would mean 0 text in the HTML file, which I think is not very usual...
What would be your advice to have the right language displayed at first, without any latency occurring ? Many thanks for your help.
I think you should make a text box on what language you want.
<!DOCTYPE html>
<html>
<head>
<title>Langtest</title>
</head>
<body>
<input type="text" id="lang" placeholder="Type a language">
<button onclick="adjust_languages()">Change!</button>
<h3 id="test">This is a test!</h3>
</body>
<script>
var sprache = document.getElementById("lang").textContent;
function adjust_languages()
{
if (sprache = "french")
{
document.getElementById("test").innerHTML = "Ceci est un test !";
}
}
</script>
</html>
Think you must need a var so no lag will happen even you have slow connection and do not use external APIs
Either translate on the server or use a client template library to translate on the client. I'd recommend mustache because it's very simple to use and lightweight. It'll make your life easier and it might run faster than your own solution.
Also if you don't want to do that anyway: use textContent instead of innerHTML. The latter needs to determine if the content is HTML or not and evaluate any element it finds while textContent just creates a text node with the string in it.

Implement a JS button - How to copy just the code and not the comment

Hello everyone and happy new year.
I do have a question regarding how to implement a little (I think not sure) JavaScript in order to copy the code inside a box, so user can directly paste into their shell.
The problem is that, the code inside the box comes from the MySQL DataBase, contains comments/descriptions/paragraphs/regular text.
You will understand what I am trying to say, please the example below:
Example, look at the command line from my website: http://www.clihelp.org/WI00261/see-the-status-of-the-w32time-service
As you can see from the page, the text inside the box titled Command Line Script could be easy to implement a JavaScript to copy the code and than paste.
But what about Example 1, Example 2, Example 3….
How can I tell the JavaScript to copy just the code and not the comments/text?
Again, look at the same issue. This is another example:
http://www.clihelp.org/LX00050/sort
Thank you so much in advance for your help.
With something like ClipboardJS you can specify exactly what to copy and from where. You will need to provide a bit of extra markup to target the relevant bit. In this case I wrapped it into a span. An example from their docs, tweaked for your case:
<!-- Target -->
<code>
Output a list of privileges
<br>
<br>
<span id="command">sc qprivs w32time</span>
</code>
<!-- Trigger -->
<button class="btn" data-clipboard-target="#command">
<img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

jQuery highlight pieces of text in an element across tags

I want to select and return searched text using jQuery.
The problem is; parts of the text may be located in <span> or other inline elements, so when searching for 'waffles are tasty' in this text: 'I'm not sure about <i>cabbages</i>, but <b>waffles</b> <span>are</span> <i>tasty</i>, indeed.', you wouldn't get any matches, while the text appears uninterrupted to people.
Let's use this HTML as an example:
<div id="parent">
<span style="font-size: 1.2em">
I
</span>
like turtles
<span>
quite a
</span>
lot, actually.
<span>
there's loads of
</span>
tortoises over there, OMG
<div id="child">
<span style="font-size: 1.2em">
I
</span>
like turtles
<span>
quite a
</span>
lot, actually.
TURTLES!
</div>
</div>
With this (or similar) JavaScript:
$('div#parent').selectText({query: ['i like', 'turtles', 'loads of tortoises'], caseinsensitive: true}).each(function () {
$(this).css('background-color', '#ffff00');
});
//The (hypothetical) SelectText function would return an array of wrapped elements to chain .each(); on them
You would want to produce this output: (without the comments, obviously)
<div id="parent">
<span style="font-size: 1.2em">
<span class="selected" style="background-color: #ffff00">
I
</span> <!--Wrap in 2 separate selection spans so the original hierarchy is disturbed less (as opposed to wrapping 'I' and 'like' in a single selection span)-->
</span>
<span class="selected" style="background-color: #ffff00">
like
</span>
<span class="selected" style="background-color: #ffff00"> <!--Simple match, because the search query is just the word 'turtles'-->
turtles
</span>
<span>
quite a
</span>
lot, actually.
<span>
there's
<span class="selected" style="background-color: #ffff00">
loads of
</span> <!--Selection span needs to be closed here because of HTML tag order-->
</span>
<span class="selected" style="background-color: #ffff00"> <!--Capture the rest of the found text with a second selection span-->
tortoises
</span>
over there, OMG
<div id="child"> <!--This element's children are not searched because it's not a span-->
<span style="font-size: 1.2em">
I
</span>
like turtles
<span>
quite a
</span>
lot, actually.
TURTLES!
</div>
</div>
The (hypothetical) SelectText function would wrap all selected text in <span class="selected"> tags, regardless of whether parts of the search are located in other inline elements like <span>, '', etc. It does not search the child <div>'s contents because that's not an inline element.
Is there a jQuery plugin that does something like this? (wrap search query in span tags and return them, oblivious to whether parts of the found text may be located in other inline elements?)
If not, how would one go about creating such a function? This function's kinda what I'm looking for, but it doesn't return the array of selected spans and breaks when parts of the found text are nested in other inline elements.
Any help would be greatly appreciated!
Piece of cake! See this.
Folded notation:
$.each(
$(...).findText(...),
function (){
...
}
);
In-line notation:
$(...).findText(...).each(function (){
...
}
);
Three options:
Use the browser's built-in methods for this. For the finding, IE has TextRange with its findText() method; other browsers (with the exception of Opera, last time I checked, which was a long time ago) have window.find(). However, window.find() may be killed off without being replaced at some point, which is not ideal. For the highlighting, you can use document.execCommand().
Use my Rangy library. There's a demo here: http://rangy.googlecode.com/svn/trunk/demos/textrange.html
Build your own code to search text content in the DOM and style it.
The first two options are covered in more detail on this answer:
https://stackoverflow.com/a/5887719/96100
Since I just so happened to be working on a similar thing right now, in case you'd like to see the beginnings of my interpretation of "option 3", I thought I'd share this, with the main feature being that all text nodes are traversed, without altering existing tags. Not tested across any unusual browsers yet, so no warranty whatsoever with this one!
function DOMComb2 (oParent) {
if (oParent.hasChildNodes()) {
for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
if (oNode.nodeType==3 && oNode.nodeValue) { // Add regexp to search the text here
var highlight = document.createElement('span');
highlight.appendChild(oNode.cloneNode(true));
highlight.className = 'selected';
oParent.replaceChild(highlight, oNode);
// Or, the shorter, uglier jQuery hybrid one-liner
// oParent.replaceChild($('<span class="selected">' + oNode.nodeValue + '</span>')[0], oNode);
}
if (oNode.tagName != 'DIV') { // Add any other element you want to avoid
DOMComb2(oNode);
}
}
}
}
Then search through things selectively with jQuery perhaps:
$('aside').each(function(){
DOMComb2($(this)[0]);
});
Of course, if you have asides within your asides, strange things might happen.
(DOMComb function adapted from the Mozilla dev reference site
https://developer.mozilla.org/en-US/docs/Web/API/Node)
I wrote a draft as a fiddle. The main steps:
I made a plugin for jQuery
$.fn.selectText = function(params){
var phrases = params.query,
ignorance = params.ignorecase;
wrapper = $(this);
. . .
return(wrapper);
};
Now I can call the selection as a $(...).selectText({query:["tortoise"], ignorance: true, style: 'selection'});
I know you want to have iterator after the function call, but in your case it is impossible, because iterator have to return valid jQuery selectors. For example:
word <tag>word word</tag> word is not valid selector.
After sanitizing the content of wrapper, for each search makeRegexp() makes personal regular expression.
Each searched piece of html source goes to emulateSelection() and then wrapWords()
Main idea is to wrap in <span class="selection">...</span> each single piece of phrase not separated by tags, but not analyze the whole tree of nodes.
NOTE:
It's NOT working with <b><i>... tags in html. You have to make corrections in regexp string for it.
I not guarantee it will work with unicode. But who knows...
As I understood, we talking about iterators like $.each($(...).searchText("..."),function (str){...});.
Check the David Herbert Lawrence poem:
<div class="poem"><p class="part">I never saw a wild thing<br />
sorry for itself.<br />
A small bird will drop frozen dead from a bough<br />
without ever having felt sorry for itself.<br /></p></div>
Actually, after rendering, browser will understood it like this:
<div class="poem">
<p class="part">
<br>I never saw a wild thing</br>
<br>sorry for itself.</br>
<br>A small bird will drop frozen dead from a bough</br>
<br>without ever having felt sorry for itself.</br>
</p>
</div>
For example, I looking for the phrase: "wild thing sorry for". Therefore, I have to highligt the exerpt:
wild thing</br><br>sorry for
I can not wrap it like this <span>wild thing</br><br>sorry for</span>, then create jQuery selector by some temporary id="search-xxxxxx", and return it back -- it's wrong html. I can wrap each piece of text like this:
<span search="search-xxxxx">wild thing</span></br><br><span search="search-xxxxx">sorry for</span>
Then I have to call some function and return jQuery array of selectors:
return($("[search=search-xxxxx]"));
Now we have two "results": a) "wild thing"; b) "sorry for". Is it really what you want?
OR
You have to write you own each() function like another plugin to jQuery:
$.fn.eachSearch = function(arr, func){
...
};
where arr will be not an array of selectors, but array of arrays of selectors, like:
arr = [
{selector as whole search},
{[{selector as first part of search]}, {[selector as second part of search]}},
...
]

change text string on couple website at the same time using jquery

22I am preparing a website which will contain prices of products on couple pages. Sometimes the same products are on couple of pages (e.g. on the main page and the specific product page). What I'm trying to achieve is to have ability of using any sort of spreadsheet or any other type of document (another perhaps) to control prices of all items across the whole website. I believe every price must be indexed somehow so we know that in with id="product1" will be the correct price and different than in id="product2".
Currently I have the example code here:
<h3>Product 1</h3>
<div class="price">
<span id="product1">£55 per day</span>
</div>
<h3>Product 2</h3>
<div class="price">
<span id="product2">£20 per day</span>
</div>
etc...
Sorry for rather a 'question type' topic than the 'case type', but I was trying to find the solution already. I know it can be done in php, but I have no idea about php unfortunately. So anything in html / javascript will be handy. Thnx a lot for any help/advice.
use JSON, not XML It's not 2003. Your jquery would be:
var prices = $.get("prices.json")
var product;
$("h3").each.( function()
{
product = $(this).html();
$(this).next().children("span").html(prices[product]);
});
Assuming you have no other H3's on your pages, otherwise give each product ID 'h3' a class a la:
<h3 class="products">Product 1</h3>
and use $(".products") instead of $("h3").
You could also use a selector to pull the <div>'s by class, and fetch the child <span>'s id.
I would recommend storing the data in either a database or an xml file to be read by the website. That way it's a "change once" situation. However, the scope of what needs to be done is beyond what you'd find in a simple answer here.
Edit: Jquery is a client side language, which means that it will only change what's currently exposed to the client at that time. It does have the ability to read from an xml file, and use that data to populate the display. But that data does need to be stored externally for it to affect more than one page at the same time.

Should I use template or return full code in jquery AJAX?

I am currently working on a project that lets users post comments with jquery and ajax. So far it is using Json and retunring several items, username, comment text, user photo url, comment ID number and stuff like that, I then need to use some sort of template to make all this data go into the correct div's before adding it all to the screen.
I am new to using javascript so this is a hard task for me. I am now considering the easy route.
Just have my PHP backend script return the whole block of code, div's and everything in place but I am wondering is this a bad idea? More importantly is it a bad idea with json?
Here is an example of a block of code that needs to be added to the screen when a comment is posted
<li class="admin" id="comment-1371">
<div class="photocolumn">
<!-- START Photo block -->
<div class="imageSub" style="width: 100px;">
<img class="male" src="http://cache2.mycrib.net/images/image_group34/0/39/T_653807517aff2b1f5662d865b40d87d527c8eb.jpg" alt="Something" width="100"/>
<div class="blackbg"></div>
<div class="label">JasonDavis</div>
</div>
<!-- END Photo block -->
</div><!-- END photocolumn -->
<div class="commenttext">
<p>02/12/3009</p>
<p>sample text for comment area!</p>
</div>
<!-- END COMMENTTEXT -->
</li>
I would say it depends on the situation/application. For instance I would use json and templating for a flight/hotel etc result screen. Why return 50k's worth of the same markup when a 4k json object will do and will allow for rapid clientside sort/filter. If you dont need quick clientside filtering/sorting then responding with dom fragments is ok. Horses for courses.
I don't see a problem with returning HTML via AJAX. A bonus of this is that you can generate most of the HTML in a view in PHP and still keep things fairly clean.
Tokenizing your data into an object is nice for re-use but can be overkill for a one-off.
Go the easy route, I can see no reasons of going with JSON array.

Categories