HTML5: Create a custom element - javascript

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.

Related

Trying to make a JQuery plugin not working

I am trying something new for me.I am always making html pages with the same functions so I want to simplify my work using a JQuery plugin made by me.But this is the First time I am trying this and I have read many web pages on how to do this and I don't know what doesn't work.This is
Emu.js file:
$.fn.loop = function(time,callback) {
setInterval(this,time);
if(callback !== 'undefined' && typeof(callback) == "function") {
callback
}
};
And this is Emu.html file:
<!DOCTYPE html>
<html>
<head>
<script src="JQuery.js" ></script>
<script src="Emu.js" ></script>
</head>
<body onload="do_it()">
<p></p>
<script type="text/javascript">
function hello() {
$("p").append("Hello!"+"<br>")
}
function do_it() {
$(hello).loop(2000)
}
</script>
</body>
</html>
jQuery plugins/ Methods (just like .show()) expect a jQuery Element Object as reference: $("p").loop()
Put the setInterval stuff within your if
Use $.proxy to refer to the right jQuery this Element Object (otherwise this will point to window Object inside setInterval)
Inside the hello() feel free to use jQuery's $(this) cause this refers to the JS reference on the HTMLParagraphElement "p"
$.fn.loop=function(time,callback) {
if(callback !== 'undefined' && typeof callback === "function") {
setInterval($.proxy(callback, this), time);
}
};
jQuery(function($) { // Use DOM ready instead of <body onload="do_it()">
function hello(){
$(this).append("Hello!<br>");
}
$("p").loop(2000,hello);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
Some errors you've could avoid your self are i.e. the use of WindowTimers.setInterval where the first parameter is supposed to be a callback function setIntarval(fn, time). this is not a function in your case.

how call a prototype function with jquery? or call prototype and jquery in footer?

for SEO reasons I try to descent js to footer in a big website make with prototype and jquery.
I try to encapsulate the jquery and prototype propertyes in the body to run after in footer I keep the variables and functions to make interactions.
with jquery works fine but i have problems with prototype.
here the idea in psedocode
<html>
<head>
<script type="text/javascript">
var domReadyQueue = []; // this var encapsule all js in the page
</script>
</head>
<body>
some Div and other tricks
<script type="text/javascript">
//<![CDATA[
domReadyQueue.push(function ($) {
new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
})
//]]>
</script>
some Div and other tricks
<script type="text/javascript">
//<![CDATA[
var loginForm;
domReadyQueue.push(function($){
loginForm = new VarienForm('login-form', true);
$('login-email').observe('keypress', bindLoginPost); //here is the error
$('login-password').observe('keypress', bindLoginPost);
})
function bindLoginPost(evt){
if (evt.keyCode == Event.KEY_RETURN) {
loginForm.submit();
}
}
function onepageLogin(button)
{
if(loginForm.validator && loginForm.validator.validate()){
button.disabled = true;
loginForm.submit();
}
}
//]]>
</script>
some Div and other tricks
<script type="text/javascript" src="http://prototype.js"></script>
<script type="text/javascript" src="http://jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
while (domReadyQueue.length) {
domReadyQueue.shift()(jQuery);
}
});
</script>
</body>
</html>
in console the error say
console error Uncaught TypeError: $(...).observe is not a function
exist a way to call prototype code with jquery?
exist a way in prototype to encapsulate? i can use this var to jquery and use other to prototype.
Maybe another idea to put jquery anf prototype in the footer? with a less impact in the rest of code?
the website have millons of lines, and works, change or re-thinks all is very complicate.

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.

Javascript learning classes questions

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.

Javascript/ASP - Not working

I must be looking wrong on this but I can't find the trick:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="http://www.listinventory.com/js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.google.com/p/jquery-utils/source/browse/trunk/src/jquery.countdown.js"></script>
<script type="text/javascript">
$(function hello() {
// function that does something exciting?
var liftOff = function () {
// ....
};
// Get a date that is some (short) time in the future
var getDeadline = function () {
var shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
return shortly;
};
// Attach click handler to all our buttons
$("div.mainpanel button.resetButton").click(function (event) {
// I am assuming that you will not be nesting these controls?
var $mainpanel = $(this).parents("div.mainpanel") // this will find the mainpanel div that contains the pressed button
.effect("highlight", {}, 700);
$("div.shortly", $mainpanel) // this will find any div with the class = shortly inside mainpanel
.countdown('change', { until: getDeadline() });
});
// Start all countdowns going on page load
$('#shortly').countdown({
until: getDeadline(),
onExpiry: liftOff,
layout: '{sn}'
});
});
</script>
<div class="mainpanel">
<div>
test
</div>
<div class="shortly">
</div>
<button class="resetButton">
Reset
</button>
</div>
</asp:Content>
I get an "Microsoft JScript runtime error: Object doesn't support this property or method" exception in the countdown.
You could try to drop the "hello" from $(function hello() {
It is not necessary.
Where is the code for the countdown method? is this in a JQuery plugin or is it a function of your own?
Is it possible the naming of $mainpanel is conflicting with something else? Try renaming this to another name (without the $).
I think it must be how you reference your plug-in code. I pasted the code in-line and it works without and error.
See here for my test: http://jsfiddle.net/3UwCg/

Categories

Resources