javascript & jquery optimization question - javascript

I am creating a website that's being localized through JavaScript, however... I have alot of pages and in each page there are alot of text inputs items, I am using this plugin
http://code.google.com/p/jquery-watermark/
to apply watermark on my inputs, now I just need guides for better performance.
Shall all watermarks be in one javascript file, or each page shall have it's own watermarks in it's own javascript file?
Shall i create one JavaScript file having all the system $(object).watermark() (I am choosing objects by classes), or each page with it's own JavaScript file must contain the jQuery watermark line of code?

TBH I wouldn't do it this way. I would apply the watermarks (or placeholders as they're known) in the HTML, like so:
<input type="text" placeholder="Hello mum!" />
And I would then use jQuery and Moderizer to determine if the current browser supports placeholders or not. If it does, you don't need to worry as the hard work's been done. If it doesn't, you can use a script like this:
if ( !Modernizr.input.placeholder )
{
$( '[placeholder]' ).focus( function()
{
var i = $( this );
if ( i.val() === i.attr( 'placeholder' ) )
{
i.val( '' );
}
}).blur( function()
{
var i = $( this );
if ( i.val() === '' )
{
i.val( i.attr( 'placeholder' ) );
}
}).blur();
}
This script essentially checks to see if the user has clicked into the input or not. If they have, it removes the placeholder as text. If they leave the input and they've left text in there, it doesn't change anything. However, if the input is empty, it then fills it with the placeholder.
I hope that helps.

General: normally you would have page specific things in a page specific javascript.
Your Problem;
assuming your html looks something like this;
<input type='text' name='bla'></input>
You could rewrite it to read;
<input type='text' name='email' class='watermark' data-watertype='email'></input>
You could apply a single javascript snippet and inlcude it throughout the page;
var texts={ "email":"Please enter a valid email address", .... },
elems=jQuery("input.watermark"),
elem,
watermarkType;
elems.each(function(i,elem){
elem=jQuery(elem);
watermarkType = texts[ elem.attr("data-watertype") ] || "";
if (watermarkType.length!==0){
//apply the watermark
elem.watermark(watermarkType);
}
}
//this isn't tested but should work as expected!
thus resolving the need of having a specific javascript for each page to apply the watermarks

Related

How can I getting textarea value using javascript and ckeditor4 [duplicate]

I'm a learner as far as JS goes and although I've spent a good few hours reading through tutorials which has helped lots but I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
What I'm trying to do is have it so that when someone types into the textarea, whatever they type appears in a div in a different part of the page.
I've got a simple text input doing that just fine but because the text area is a ckEditor the similar code doesn't work.
I know the answer is here: ckEditor API textarea value but I don't know enough to figure out what I'm meant to do. I don't suppose anyone fancies helping me out?
The code I've got working is:
$('#CampaignTitle').bind("propertychange input", function() {
$('#titleBar').text(this.value);
});
and
<label for="CampaignTitle">Title</label>
<input name="data[Campaign][title]" type="text" id="CampaignTitle" />
and
<div id="titleBar" style="max-width:960px; max-height:76px;"></div>
I'm still having problems figuring out exactly how I find out what a
user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article:
http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id of element assigned the editor.
You could integrate a function on JQuery
jQuery.fn.CKEditorValFor = function( element_id ){
return CKEDITOR.instances[element_id].getData();
}
and passing as a parameter the ckeditor element id
var campaign_title_value = $().CKEditorValFor('CampaignTitle');
i found following code working for ckeditor 5
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.model.document.on( 'change:data', () => {
editorData = editor.getData();
} );
} )
.catch( error => {
console.error( error );
} );
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
you can add the following code :
the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

get value from localStorage and append it to class

I'm messing around with setting data into localStorage, but I'm trying to extract a value and have it populate into an empty span on a specific page load.
This is what I've been messing with, but I'm not sure if this is the correct way to go about it:
if($(".body-class-name").length > 0){
$('.title span').append($(localStorage.getItem("first_name")));
}
The only other examples I've tried to work with deal with external JSON data and that's a little too much for what I'm trying to work with.
The code does what it is suppose to. You could improve abit.
if($(".body-class-name").length > 0){
var firstname = $(localStorage.getItem("first_name");
if (firstname) {
$('#title-text').text(firstname));
}
}
Then there is some missing context in your post. But i would also look at:
Using text instead of append if you don\t want to keep append firstnames to that span.
And as others mentioned in comments be aware of your selector. I changed it to query for an ID instead.
if ( $ ( ".body-class-name" ). length > 0 ){
$ ( '.title span' ). append ( localStorage . getItem ( "first_name" )); }
The $() isn't needed around the localStorage.getItem()
You don't need using load event.
Load event is for assets files, you can use ready event.
In basically jQuery code run after document ready.
You just need to wrap with function, For example:
<h1 class="title">Hello again <span>User</span></h1>
<br/>
<label>
Enter your name here:
<input name="firstname" />
</label>
<script>
(function($){
$("input[name='firstname']").change(function(){
// Store
localStorage.setItem("first_name", $(this).val() );
});
// Load store
$('.title span').text( localStorage.getItem( "first_name" ) );
})(jQuery);
</script>
Live code here

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

Can jQuery or Javascript change elements within textareas?

My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/

Getting the textarea value of a ckeditor textarea with javascript

I'm a learner as far as JS goes and although I've spent a good few hours reading through tutorials which has helped lots but I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
What I'm trying to do is have it so that when someone types into the textarea, whatever they type appears in a div in a different part of the page.
I've got a simple text input doing that just fine but because the text area is a ckEditor the similar code doesn't work.
I know the answer is here: ckEditor API textarea value but I don't know enough to figure out what I'm meant to do. I don't suppose anyone fancies helping me out?
The code I've got working is:
$('#CampaignTitle').bind("propertychange input", function() {
$('#titleBar').text(this.value);
});
and
<label for="CampaignTitle">Title</label>
<input name="data[Campaign][title]" type="text" id="CampaignTitle" />
and
<div id="titleBar" style="max-width:960px; max-height:76px;"></div>
I'm still having problems figuring out exactly how I find out what a
user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article:
http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id of element assigned the editor.
You could integrate a function on JQuery
jQuery.fn.CKEditorValFor = function( element_id ){
return CKEDITOR.instances[element_id].getData();
}
and passing as a parameter the ckeditor element id
var campaign_title_value = $().CKEditorValFor('CampaignTitle');
i found following code working for ckeditor 5
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.model.document.on( 'change:data', () => {
editorData = editor.getData();
} );
} )
.catch( error => {
console.error( error );
} );
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
you can add the following code :
the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

Categories

Resources