Error building my first Javascript library - javascript

I´ve doing some work in Javascript for my ASP.NET application. I got after a while a lot of views with extensive Javascript functionalities, but all replicated in different views. Now I decided I have to make things easier and decided to start building my own Javascript libraries.
So, this is the code I first came for, to have a paintedText that I will control on screen (this is a library prototype, so I took a simple function to test. Of course this can be done easily without a library).
The library:
/*
* My first Javascript library
*/
paintedText = (function () {
"use strict";
paintedText = paintedText || {};
paintedText = (function (id) {
//Private Property
var version = "1.0.0";
//Public Property
var color = null;
var elementId = id;
//Public Method
setColor = function (color) {
var dom = getMyDOM(document.getElementById(id));
domElement.style = "color : " + color;
}
//Private Method
function getElementObj() {
if (elementId === undefined)
alert("Undefined " + elementId);
else
return document.getElementById(elementid);
}
})
})
And the index.html page:
<head>
<script type="text/javascript" src="myLib.js"></script>
</head>
<body>
<div id="test">
<h1>TEXT TO CHANGE COLOR</h1>
</div>
<script type="text/javascript">
$(document).ready(function () {
var item = new paintedText ('test');
alert ('Will change color.');
item.setColor('red');
});
</script>
</body>
I keep receiving a message that paintedText does not exists and I´m stuck with that. I hope someone can help me to move further...
So the questions are:
Why is that code not working ?
Is my code protected (I need to insert into my pages and make
sure my variables will be unique) ?
Thanks a lot for the help.

For starters, if you want to create an instance of an IIFE, you need a constructor function.
Also, dom is define inside its own function.
How about something like this:
var PaintedText = (function(){
function pt(id){
this.element = document.getElementById(id);
}
pt.prototype.setColor = function(color){
if(!this.element) throw new ReferenceError('element not found');
this.element.style.color = color;
};
return pt;
})();
var pt = new PaintedText('test');
pt.setColor('red');
http://jsfiddle.net/U6KS2/

Related

Why isn't this working - JS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on a project to check to see if a new items is updated on a website. I want to the program to check every second to see if a new item has come in. The items are designated by an ID (which I can get). However, I am having trouble using AJAX to update the part of the website. I want it to 'refresh' the website every second and compare the most recent item to its previous most recent item (i.e. if current > past). Any help would be much appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button onclick = "body()">Click Me</button>
<script>
var highest = 0;
var compare = 0;
var creator;
var newItem = false;
var HelpPeople = 'People's Names';
var elements = document.getElementsByClassName('ms-itmhover');
highest = elements[0].getElementsByClassName('ms-vb2')[1].innerText;
var body = function()
{
window.setTimeout(update(), 1000);
}
var update = function()
{
window.jquery-2('body').load('URL');
elements = document.getElementsByClassName('ms-itmhover');
compare = elements[0].getElementsByClassName('ms-vb2')[1].innerText;
creator = elements[0].getElementsByClassName('ms-vb-user')[0].innerText;
if(compare > highest && creaCompare(creator))
{
displayNew();
}
body();
}
var creaCompare = function(create)
{
var comparer = false;
for(var i = 0; i < HelpPeople.length; i++)
{
if(create == HelpPeople[i])
{
comparer = true;
}
}
return comparer;
}
var displayNew = function()
{
confirm('There is a new item');
body();
}
</script>
</body>
I think I asked the question wrong. I am looking to run this on a website (not my own) and have it parse out data and check for new items (AJAX). I am wondering how to use it and how I can use JS on this website (can I run it through the console?)
I rewrote your code because you're using jQuery... but not using it.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js"></script>
</head>
<body>
<button id="btnTest">Click Me</button>
<script type="text/javascript">
// wait for document loaded
$(function () {
var updateUrl = 'put your update url here';
var highest = 0;
var compare = 0;
var creator;
var newItem = false;
var HelpPeople = 'People's Names';
var elements = $('.ms-itmhover'); // where's this element
highest = $('.ms-vb2', elements).text(); // where are those elements ????
var body = function () {
$('#btnTest").prop('disabled', true);
setTimeout(update, 1000);
};
var update = function()
{
$('body').load(updateUrl, function (response, status, xhr) {
if ( status == "error" ) {
alert("Sorry but there was an error : " + xhr.status + " " + xhr.statusText);
return;
}
elements = $('.ms-itmhover');
compare = $('.ms-vb2', elements).text();
creator = $('.ms-vb-user', elements).text();
if (compare > highest && creaCompare(creator))
{
displayNew();
}
body();
});
};
var creaCompare = function(create) {
var comparer = false;
for (var i = 0; i < HelpPeople.length; i++)
{
if(create == HelpPeople[i]) {
comparer = true;
}
}
return comparer;
};
var displayNew = function() {
confirm('There is a new item');
body();
};
// prevent button click more than once
$('#btnTest").one('click', body);
});
</script>
</body>
As for answering the actual question, without more HTML, there's not much that can be answered. But the above change presumably fixes :
Executing JS code before document is loaded; now wait until page has loaded
Properly make use of jQuery's DOM traversal and manipulation functions.
Better HTML/JS separation
Encapsulate variables in "private" scope (prevent global namespace pollution) (thank you George Mauer)
You had invalid variable names (i.e. jquery-2 is not what you expect, and 2(..) is an invalid syntax)
Your had setTimeout(update(), 1000); which does nothing since it's essentially doing setTimeout(undefined, 1000);
You processed your updated HTML perhaps before it was even loaded (Ajax is async!)
What this answer does not cover :
What is the actual error (the question does not really specify)
Give a concrete working solution, since parts of the HTML is missing
The problem is probably on this line:
window.jquery-2('body').load('URL');
It's not even a valid syntax. It should be written like this:
$('body').load('URL'); // Instead of 'URL' there also should be a proper URL
Also you should know the load function is asynchronous so if you need to do something with loaded elements, you need to put these actions in a callback. (A function passed as a second arguments of the load method.)

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

FCKEditor: Access content area

I'm having problems doing this. I can't access the content area object. I need it to attach a click listener.
var oFCKeditor = new FCKeditor( editorName ) ;
oFCKeditor.BasePath = o.editorPath;
if (o.configPath) {
oFCKeditor.Config["CustomConfigurationsPath"] = o.configPath +"?" + ( new Date() * 1 ) ;
}
oFCKeditor.Width = '100%';
oFCKeditor.Height = '100%';
oFCKeditor.ReplaceTextarea();
oFCKeditor.setEnabled(true);
alert(oFCKeditor.EditorDocument);
alert(oFCKeditor.EditorWindow);
alert(FCK);
I also tried accessing there objects from different parts inside FCKEditor's code, but no luck.
What am I doing wrong? What is the usual way to do this?
Thanks
Edit: when I do this:
var oEditor = FCKeditorAPI.GetInstance(editorName) ;
alert(oEditor.EditorDocument);
after creating the editor it works, but only when I'm stepping through it with a debugger, otherwise it's undefined. So it's probably a timing issue. But where am I supposed to get that then?
http://docs.cksource.com/FCKeditor_2.x/Developers_Guide/JavaScript_API#Events
<script type="text/javascript">
var object;
function FCKeditor_OnComplete(editorInstance)
{
object = editorInstance;
}
function Display()
{
alert( object.GetHTML());
}
</script>

Help me simplify this JS code

I'm a beginner in JS and want to know a way to simplify this code. There are 7 different divs with iframes, and also 7 different links. I have shown 1 div with iframe and 1 link. I have no idea where to start. Any help would be greatly appreciated.
NOTE: The code works to my needs, but I just need to simplify it (less js code in html, and more in js file).
JavaScript in .js file:
function show_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "block";}
}
function hide_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "none";}
}
function refFrame() {
for(var i = 0,e = arguments.length;i < e;i++){
document.getElementById(arguments[i]).src = document.getElementById(arguments[i]).src;
}
}
Div/iframe to be modified:
<div id="r1-box">
<iframe id="frame-box1" class="work" src="youtubelink" width="720" height="405" frameborder="0"></iframe>
</div>
Link to execute JS:
<a id="r1" href="javascript:refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');show_visibility('r1-box');hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');">
</a>
As a beginner you shouldn't start using jQuery until you understand Javascript more.
There are a few ways you could simplify this, the most immediate one would be to get the Javascript out of the link and into a Javascript file, or at the top of the page:
window.onload = function() {
document.getElementById('#r1').onclick = function() {
refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');
show_visibility('r1-box');
hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');
};
// more...
};
window.onload is an event which fires once the page has - you guessed it - finished loading. There are better ways of doing this, but this is about as basic as it gets. I'd advise you look at javascript domready?
After looking at your code a bit more, I realised all your seven links will do essentially the same thing. You can simply this by using a single function:
function refClick(id) {
var i = 7,
frames = [],
boxes = [];
while(i--) {
if(i != id) {
frames.push('frame-box' + i);
boxes.push('r' + i + '-box');
}
}
refFrame.apply(null, frames);
hide_visibility.apply(null, boxes);
show_visibility('r' + id + '-box');
}
What I'm doing here is looping through 7 times, and building an array of arguments for the refFrame and hide_visibility functions. The id variable tells the loop not to put in that id into the arrays.
Using the .apply method, I can apply an array as the arguments and call it normally.
For each of your links, you can apply the following function
document.getElementById('#r1').onclick = function() {
refClick(1);
};
document.getElementById('#r2').onclick = function() {
refClick(2);
};
//.....
You could start using jQuery.
http://jquery.com/

How to make custom script into Jquery like plugin

I have writtern a script to limit the number of characters in the textarea, and the code is here
<script>
function limitchar(charcount, counterId, msgId)
{
var tex = document.getElementById(msgId).value;
var len = tex.length;
if(len > charcount)
{
alert("Content Limit Exceeded");
tex = tex.substring(0,charcount);
document.getElementById(msgId).value =tex;
return false;
}
document.getElementById(counterId).innerHTML = charcount-len;
}
</script>
I am calling the function as
<textarea name="txtar1" id="txtar1" onkeyup=limitchar('10','verid','txtar1')></textarea>
I dont want these kind of ugly function call, since my textareas are dynamically generated
Like Jquery, I want my function to be called like
$('txtar1').limitchar();
Is there anyother way to achieve this. Thanks Experts! in advance
ANSWER :
Thanks for andy rose. I used his approach. Here is my final code:
<script>
$(document).ready(function() {
$('#txtar1').keydown(function() {
limiter('10', 'verid' , this.id);
});
});
</script>
<textarea name="txtar1" id="txtar1"></textarea>
<span id="verid">10</span>
<script>
/* Will use as common.js */
function limiter(charcount,showcountid,msgId)
{
var tex = document.getElementById(msgId).value;
var len = tex.length;
if(len > charcount)
{
//alert("Content Limit Exceeded");
tex = tex.substring(0,charcount);
document.getElementById(msgId).value =tex;
return false;
}
document.getElementById(showcountid).innerHTML = charcount-len;
}
</script>
You might want to look at this blog entry from Mike Alsup in which he explains a pretty good pattern on how to develop a jQuery-Plugin. He also goes into very much details about further development and extending the basic plugin.
Rather than creating a new plugin why not use one of jQuery's key events:
$('txtar1').keydown(function() {
...stuff here
});
It's easy. Just do:
$.fn.limitchar = function () {
var $items = $(this);
};
$items will be a jQuery object equivalent to $('txtar1').

Categories

Resources