How to make custom script into Jquery like plugin - javascript

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').

Related

Javascript that changes HTML code

Is it possible to make javascript to when you enter variables to add code to html..? I don't know English too good, so..I'm going to draw it!
Also, I don't want it to change everything, but I want it just to add that
info to the list..I have premade HTML page with linked CSS.
If you have any questions, please ask me, just help me.. :(
I know HTML and CSS, java..Not even a little bit.. :/
If you are here reading this, THANK YOU! <3
You have many options to add html to your page through JavaScript.
1) Simply create a div with an id
<div id="enterTextHere"></div>
2) Inside of your custom.js file or inside of <script></script>, you can use many different methods
Method 1 : Using innerHTML
var desiredElement = document.getElementById("enterTextHere");
desiredElement.innerHTML = "<p>I added text!</p>";
Method 2 : Using JQuery.append
$("#enterTextHere").append("I added text!");
I'm sure there are many more but without your specific code to reference this is the best I can do. Please use this link for your reference. It also has a lot of good information for the rest of your HTML journey. Enjoy! w3schools
Maybe something like this can help:
HTML:
<table class="table"><tr id="update-table"></tr></table>
<script>
(function(){
var updater = (function(){
function updater( options ){
this.table = options.table;
this.cells = this.table.querySelectorAll('.cell');
this.num_cells = this.cells ? this.cells.length : 0;
}
updater.prototype.update_element = function( index, value ){
this.cells[index].innerHTML = value;
};
updater.prototype.add_element = function(){
var td = document.createElement('td');
td.setAttribute('class','cell');
this.table.appendChild(td);
this.cells.push(td);
this.num_cells++;
};
return updater;
})();
window.updater = updater;
})();
var table, a, count = 0;
table = document.getElementById('update-table');
a = new updater({table:table});
for(var i = 0; i < 5; ++i){
a.add_element();
a.update_element(i,'info'+i);
}
</script>

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.)

Error building my first Javascript library

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/

JavaScript/jQuery: hasDescendant / hasAncestor

Hilariously, I'm having incredible difficulty finding any half-good way to determine whether or not an HTML element is inside another one or not -- which seems like it should be a basic core feature of traversing and analyzing the HTML DOM. I was immensely surprised and disappointed that the "hasDescendant" (or likewise) method is missing.
I'm trying to do this:
var frog = $('#frog');
var walrus = $('#walrus');
if (frog.hasDescendant(walrus)) console.log("Frog is within walrus.");
else console.log("Frog is outside walrus.");
I've tried to reproduce what I'm looking for with many jQuery combinations.
walrus.is(frog.parents());
walrus.has(frog);
walrus.find(' *').has(frog);
frog.is(walrus.find(' *'));
I haven't found a working solution yet.
[edit]
Solution: walrus.has(frog)
Alternate: if (walrus.has(frog)) { doStuff(); }
Alternate: var booleanResult = walrus.has(frog).length>0;
//Chase.
jQuery has just the function for this: jQuery.contains: "Check to see if a DOM element is within another DOM element."
Demo (live copy):
HTML:
<p id="frog">Frog <span id="walrus">walrus</span></p>
JavaScript:
jQuery(function($) {
var frog = $("#frog"),
walrus = $("#walrus");
display("frog contains walrus? " + $.contains(frog[0], walrus[0]));
display("walrus contains frog? " + $.contains(walrus[0], frog[0]));
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Use
if (walrus.has(frog).length) {
// frog is contained in walrus..
}
Demo at http://jsfiddle.net/gaby/pZfLm/
An alternative
if ( $('#frog').closest('#walrus').length ){
// frog is contained in walrus..
}
demo at http://jsfiddle.net/gaby/pZfLm/1/
If you wanted to write your own function you could do it without jQuery, perhaps something like this:
function isAncestor(ancestor, descendent) {
while ((descendent = descendent.parentNode) != null)
if (descendent == ancestor)
return true;
return false;
}

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/

Categories

Resources