Javascript learning classes questions - javascript

I've been working with javascript for a while but never made any classes and my work has been getting messy with tons of unorganized functions. So now I am learning how to use classes, and I have question.
How can I execute functions within a class, example:
<html>
<head>
<script type="text/javascript">
window.onload = function (){
var object = new testClass("test123");
alert(object.content);
}
function testClass (id){
this.object = document.getElementById(id);
this.content = this.getContent(); //<- this is what I want to do
this.getContent = function (){
return this.object.innerHTML;
}
}
</script>
</head>
<body>
<div id="test123">Hello World</div>
</body>
</html>
Basically how can i call upon function inside of the class inside of the class? In the example how can I get this.getContent to return "Hello World".
I know I can do it like :
<html>
<head>
<script type="text/javascript">
window.onload = function (){
var object = new testClass("test123");
alert(object.getContent());
}
function testClass (id){
this.object = document.getElementById(id);
this.getContent = function (){
return this.object.innerHTML;
}
}
</script>
</head>
<body>
<div id="test123">Hello World</div>
</body>
</html>
I am using chrome to test. I am doing this wrong, can it be done? Thanks in advance.

You're calling getContent before creating it.
Move the function call below the assignment.

Related

HTML5: Create a custom element

I'm trying to create custom element that has a function which can be called from Jscript, but I can't get it working and don't see what's wrong...
My code:
<html>
<head>
<script language="javascript" type="text/javascript">
var XFooPrototype = Object.create(HTMLButtonElement.prototype);
XFooPrototype.foo = function() {
alert("foo");
}
document.registerElement('x-foo', {
prototype: XFooPrototype
});
document.addEventListener("DOMContentLoaded", function(event) {
var mytag = document.getElementById("my_tag");
mytag.foo();
});
</script>
</head>
<body>
<x-foo id="my_tag"></x-foo>
</body>
</html>
I would excpted that foo() is called and "foo" alert appears, but instead foo() is not defined when I call it.
Can someone point me to what's wrong on this?
(I know I should use class / extend and customElements.define, but this need to run on older browsers too)
Thanks!
document.registerElement is deprecated in favor of customElements.define(). document.registerElement is deprecated even before most of the browsers knew this.
Therefore your current code should not work in most cases. New way of creating a custom element is-
<html>
<head>
</head>
<body>
<x-foo id="my_tag"></x-foo>
<script language="javascript" type="text/javascript">
class MyElement extends HTMLElement {
constructor() {
super()
}
foo() {
alert("foo");
}
}
window.customElements.define('x-foo', MyElement);
document.addEventListener("DOMContentLoaded", function(event) {
var mytag = document.getElementById("my_tag");
mytag.foo();
});
</script>
</body>
</html>
Currently Chrome supports this. Others are coming.
Custom element that older browsers can support can be created using Polymer.

calling js namesapce funcitons from html

As it is evident from below question I am new to html/js and forgive me if this question was asked previously.
All I am trying to do is call a js function defined in namespace from html and I cannot get this to work.
When I click on "Alert!!" button, it should invoke myAlert function defined in sample.js file, but it is not working..Can you help me please?
Here is my sample.js file..
var mytest = mytest || {};
(function ($) {
function youhere() {
alert("You are Here!!");
}
function myAlert() {
alert("YouMadeIt");
}
function funcInit() {
youhere();
}
mytest.funcInit = funcInit;
}(jQuery));
And html file:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Sample</TITLE>
<script type="text/javascript" src="./js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="./js/sample.js"></script>
</HEAD>
<script>
$(document).ready(function() {
mytest.funcInit();
});
function testBtnClk() {
mytest.myAlert();
}
</script>
<BODY>
<input type="button" id="testbtn" onclick="testBtnClk();" value="Alert!!" />
</BODY>
</HTML>
Because myAlert is not a property of mytest.
The function myAlert is a closure function which exists only inside the IIFE, it is not accessible outside of that IIFE. Since you have a global namespace you can add the function reference to that so that you can use that reference to call the method outside of the IIFE.
var mytest = mytest || {};
(function ($) {
function youhere() {
alert("You are Here!!");
}
function myAlert() {
alert("YouMadeIt");
}
function funcInit() {
youhere();
}
mytest.funcInit = funcInit;
mytest.myAlert = myAlert;
}(jQuery));
Demo: Fiddle

Scope issue in html page with javascript

I believe this is a scope issue but I haven't been able to resolve it, you can see some of the things I have tried commented out, maybe you can solve it. I have a variable, for purposes of StackOverflow I have named it undefinedVar and I try to call a method owned? by that variable but when I do I get Uncaught ReferenceError: undefinedVar is not defined. Now, there is obviously a whole lot more in this .html file but none of that matters for this question.
<!DOCTYPE html>
<html>
<head>
<script>
varX.ready(functionName);
function functionName() {
varX.ready(unDefinedVar.itsFunction());
};
</script>
</head>
<body>
<div id="#stackOverflow">
<div id="demo"></div>
</div><!-- End of the #stackOverflowDiv -->
</body>
<script>
//$(document).ready( function () {
//$( function () {
unDefinedVar = kendo.observable({
randomVariable: [],
itsFunction: function () {
#blahblahblah
}
});
//}); //end $function
//}); //End Document.ready
</script>
</html>
..or what would be the proper way to make this work?
You need to put the function after you've defined undefinedVar, so it looks like this:
undefinedVar = kendo.observable({
randomVariable: [],
itsFunction: function () {
#blahblahblah
}
});
function functionName() {
varX.ready(undefinedVar.itsFunction());
};
varX.ready(functionName);
Also, you've defined undefinedVar, but are looking to reference unDefinedVar. Make sure the case matches!

Need help understanding Javascript setinterval and function declaration

I am very new to js and jquery and need help understanding why this script does not work. I've checked it over any number of times, but in all my research, there is something that I am missing. Any help would be appreciated. The code should just set text value in div once every 2 seconds. I cut this code down from its real functionality so ignore the fact that it does nothing. Forgive and correct me if I am not posting this properly. It's my first post.
code below:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var test=0;
var timer = setInterval(save_it(), 2000);
var test=0;
$(document).ready(function(){
var save_it = function(){
testdiv.innerhtml = test++;
};
});
</script>
</head>
<body>
<div id="testdiv"></div>
</body>
</html>
Try this example (jsFiddle http://jsfiddle.net/Br59d/)
HTML:
<div id="testdiv"></div>
javascript:
var test=0;
$(document).ready(function(){
var timer = setInterval(save_it, 2000);
});
function save_it(){
$('#testdiv').html(test.toString());
test++;
};
To provide some input:
var save_it = function() {
and
function save_it() {
act two separate ways. If you use var save_it = function() you can't call that function before the declaration.
i.e. you couldn't do this:
save_it();
var save_it = function() {
alert('k');
}
however, if you use function save_it() you can.
save_it();
function save_it() {
alert('k');
}
JSFiddle: http://jsfiddle.net/jeffshaver/nmSD6/

How to add and call functions from constructors in Javascript (uses JQuery)

I have created an object literal using the code below. Everything works fine.
However, when I attempt to rewrite the object literal by creating an object constructor and a corresponding object, and then execute the method using the "dot syntax" nothing happens. I am unclear what I am doing wrong. The example below uses JQuery.
Thank you.
Object literal (working)
<!DOCTYPE=HTML>
<meta chartset="UTF-8">
<title> whatever </title>
<script type="text/javascript"> </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" charset="utf-8"></script>
<div id="theDiv"></div>
<style>
#theDiv{
position:absolute;
width:200px;
height:200px;
background:#f00;
}
</style>
<script>
$(document).ready(function(){
var myObj = {};
myObj.doThing = function () {
$("#theDiv").toggle(3000);
};
myObj.doThing();
});
</script>
Constructor with object (non-working)
<!DOCTYPE=HTML>
<meta chartset="UTF-8">
<title> whatever </title>
<script type="text/javascript"> </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" charset="utf-8"></script>
<div id="theDiv"></div>
<style>
#theDiv{
position:absolute;
width:200px;
height:200px;
background:#f00;
}
</style>
<script>
$(document).ready(function(){
function ConstructorExample (){
this.move = function () {
$("#theDiv".toggle(3000);
};
};
var objExample = new ConstructorExample();
objExample.move();
});
</script>
You have syntax error in your second example.
Change this:
$("#theDiv".toggle(3000);
to this:
$("#theDiv").toggle(3000);
This is not to fix your problem (since Joseph has answered), but a better practise for your reference:
Change from:
function ConstructorExample (){
this.move = function () {
$("#theDiv").toggle(3000);
};
};
Change to:
var ConstructorExample = function ConstructorExample () {
this.node = $("#theDiv");
};
ConstructorExample.prototype.move = function () {
if (!!this.node) {
this.node.toggle(3000);
}
};
It behaves the same, but by using the prototyped chain, it do not create the move function every time you initiate the object (faster in speed), and it can be prototype inherited.

Categories

Resources