javascript namespace issue jsfiddle - javascript

I have code here http://jsfiddle.net/morenoh149/HWbuv/1/
this should be an easy fix. Why is itemClicked not being found?
my html
13" tortilla<input id="1" type="checkbox" onClick="itemClicked()">
<a id="console">the</a>
the relevant javascript
function itemClicked(element, id) {
if (element.checked) {
list.push(item[id]);
addItem(item[id]);
} else {
for (x in list) {
if (list[x].id == id) list.splice(x, 1);
}
subtractItem(item[id]);
}
var e = document.getElementById("console");
e.innerHTML = "blah";
}

jsFiddle puts the code inside window.onload handler function, so if you declare a function in the Javascript panel it isn't global.
Make it global by assigning it to window:
function itemClicked(element, id) {
/...
}
window.itemClicked = itemClicked;
Or alternatively:
window.itemClicked = function(element, id){...}

Related

DOM Traversal API

I am tryingto get the parent of nodes. I tried these.
Ist Approach:
function update(currentElement) {
document.getElementById("nodeNameField").value = currentElement.nodeName;
document.getElementById("nodeTypeField").value = currentElement.nodeType;
document.getElementById("nodeValueField").value = currentElement.nodeValue;
}
function nodeMove(direction) {
switch (direction)
{
case "parentNode": if (nodeMove.currentElement.parentNode)
nodeMove.currentElement = nodeMove.currentElement.parentNode;
else
alert("No parent");
}
update(nodeMove.currentElement);
}
window.onload = function () {
document.getElementById("parentBtn").onclick = function () {nodeMove("parentNode")};
nodeMove.currentElement = document.documentElement; // HTML
update(nodeMove.currentElement);
}
Since the current element is HTML, when i click on the parent button, I do get #document as it's parent.
2nd approach:
if (document.createTreeWalker) {
function myFilter(n) {
return NodeFilter.FILTER_ACCEPT;
}
var myWalker = document.createTreeWalker(document.documentElement,NodeFilter.SHOW_ALL,myFilter, false);
} else
alert("Error: Browser does not support DOM Traversal");
function update(currentElement) {
window.document.testform.nodeName.value = currentElement.nodeName;
window.document.testform.nodeType.value = currentElement.nodeType;
window.document.testform.nodeValue.value = currentElement.nodeValue;
}
var currentElement = myWalker.currentNode;
//var currentElement = document.documentElement;
update(currentElement);
</script>
<form>
<input type="button" value="Parent" onclick="myWalker.parentNode();update(myWalker.currentNode);">
In the 2nd case, i am unable to get the parent of HTML. How will I resolve it? Any suggestions?
If you declare myWalker inside if scope, it won't be visible for outer/global scope. Move declaration over this scope like here:
var myWalker;
if (document.createTreeWalker) {
function myFilter(n) {
return NodeFilter.FILTER_ACCEPT;
}
myWalker = document.createTreeWalker(document.documentElement,NodeFilter.SHOW_ALL,myFilter, false);
} else
alert("Error: Browser does not support DOM Traversal");
function update(currentElement) {
window.document.testform.nodeName.value = currentElement.nodeName;
window.document.testform.nodeType.value = currentElement.nodeType;
window.document.testform.nodeValue.value = currentElement.nodeValue;
}

Javascript - Uncaught ReferenceError - Code seems perfect?

Here's how I'm calling my JS:
"#item.OwnerID#" is a variable from a loop containing an ID. So the element I want to change the CSS for should look like: "cwa123" or some other number for the id...
Here's my JS:
$(document).ready(function() {
function toggleChatControl(id){
var wnd = document.getElementById(id);
if (wnd.style.marginBottom == '-1px') {
wnd.style.marginBottom = '-236px';
} else {
wnd.style.marginBottom = '-1px';
}
}
});
I ain't got a clue, it gives me the "not defined" error...
Out of scope, remove the document ready wrapper
function toggleChatControl(id){
var wnd = document.getElementById(id);
if (wnd.style.marginBottom == '-1px') {
wnd.style.marginBottom = '-236px';
} else {
wnd.style.marginBottom = '-1px';
}
}
Every function creates a new scope, the global scope is window, and that's the scope used for inline javascript.
Inside $(document).ready(function() { ... }); the scope is changed (to document) so the function is out of scope for the inline handler.
An even better approach would be to use a proper event handler
$('.FCChatControl').on('click', function() {
toggleChatControl('cwa#item.OwnerID#');
});

Jquery check if var is a function and then call it

I have a variable name that I pass into a plugin, but the variable is actually a function.
I use jquery $.isFunction to check if it is a function, and if it is, it should execute the function.
But I can't seem to make it work, I put some examples in jsfiddle:http://jsfiddle.net/tZ6U9/8/
But here is a sample code:
HTML
<a class="one" href="#">click</a><br />
<a class="two" href="#">click</a><br />
<a class="three" href="#">click</a><br />
JS
$(document).ready(function() {
help = function(var1) {
alert(var1);
}
function help2(var1) {
alert(var1);
}
$('a.one').click(function() {
var functionName = "help";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
$('a.two').click(function() {
var functionName = "help";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.three').click(function() {
var functionName = "help2";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.four').click(function() {
var functionName = "help2";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
});​
As you can see, I tired a bunch of things, but all the wrong ones probably...
I inspired some of them from: jQuery - use variable as function name
Overall
I'm passing a variable that has the same name as a function, using jquery to check if it is a function, if it is, it should execute the function.
Thanks in advance for your help.
If you are wanting to call a function by a string of its name just use window.
var functionName = "help";
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
} else {
alert("not a function");
}
You can use the following to invoke functions that are defined in the window/global scope, such as the function help:
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
}
help2, on the other hand, is not accessible this way since you are defining it in a closure. A possibile solution is to define the function outside of the .ready() handler. Then, you can use window[functionName] to call it:
var namespace = {
help: function (var1) {
alert(var1);
},
help2: function (var1) {
alert(var1);
}
}
$(document).ready(function() {
var functionName = "help";
if ($.isFunction(namespace[functionName])) {
namespace[functionName]("hello");
}
});
DEMO.
Check Fiddle for the working example.
Example have only one link working. make other links similarly.
Edit: after first comment
HTML
<a class="one" href="#">click</a><br />
JS
var help = function(var1) {
alert(var1);
}
$(document).ready(function() {
$('a.one').click(function() {
var functionName = help;
if ($.isFunction(functionName)) {
functionName('test');
} else {
alert("not a function");
}
return false;
});
});​

javascript combining public and private window.onload

i am currently learning about javascript namespaces as i build a website and i have the following requirements: i want to make all of my code private so that other public scripts on the page (possibly adverts, i'm not too sure at this stage) cannot override or alter my javascript. the problem i am foreseeing is that the public scripts may use window.onload and i do not want them to override my private version of window.onload. i do still want to let them run window.onload though.
so far i have the following layout:
//public code not written by me - i'm thinking this will be executed first
window.onload = function() {
document.getElementById('pub').onclick = function() {
alert('ran a public event');
};
};
//private code written by me
(function() {
var public_onload = window.onload; //save the public for later use
window.onload = function() {
document.getElementById('priv').onclick = function() {
a = a + 1
alert('ran a private event. a is ' + a);
};
};
if(public_onload) public_onload();
var a = 1;
})();
i have quite a few questions about this...
firstly, is this a good structure for writing my javascript code, or is there a better one? (i'm planning on putting all of my code within the anonymous function). is my private code really private, or is there a way that the public javascript can access it? i'm guessing the answer to this is "yes - using tricky eval techniques. do not embed code you do not trust", but i'd like to know how this would be done if so.
secondly, when i click on the public link, the event is not fired. why is this?
finally, if i comment out the if(public_onload) public_onload(); line then a is returned correctly when i click the private button. but if i leave this line in then a's value is nan. why is this?
You can attach event listeners to avoid their overriding in some way like this:
<ol id="res"></ol>
<script type="text/javascript">
var res = document.getElementById('res');
function log(line) {
var li = document.createElement('li');
li.innerHTML = line;
res.appendChild(li);
}
// global code:
window.onload = function() {
log('inside the global window.onload handler');
};
// private code:
(function(window) {
function addEvent(el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
} else {
el['on' + ev] = fn;
}
}
addEvent(window, 'load', function() {
log('inside the second window.onload handler in "private section"');
});
})(window);
</script>​
DEMO
The example of code organization you asked about:
HTML:
<ol id="res"></ol>​
JavaScript:
/* app.js */
// in global scope:
var MyApp = (function(app) {
var res = document.getElementById('res');
app.log = function(line) {
var li = document.createElement('li');
li.innerHTML = line;
res.appendChild(li);
};
app.doWork = function() {
app.log('doing a work');
};
return app;
})(MyApp || {});
/* my-app-module.js */
// again in global scope:
var MyApp = (function(app) {
app.myModule = app.myModule || {};
app.myModule.doWork = function () {
app.log('my module is doing a work');
};
return app;
})(MyApp || {});
/* somewhere after previous definitions: */
(function() {
MyApp.doWork();
MyApp.myModule.doWork();
})();
​DEMO
MyApp is accessible from outside
Nothing is accessible from outside

Trigger an actionscript function (in a flash object) from javascript

I have a flash (AS2.0) application with a function that i need to trigger from a html form link
The flash function only runs a gotoAndPlay('label name');
So my HTML is
<a href="" id="flashTrigger" />
and my flash function is
function myFunction(){
gotoAndPlay("myLabel");
}
Anyone know either how I can fire the flash function from the html link tag, OR run a "gotoAndPlay" from a Javascript function
Iv looked around and only seem to find how to fire a javascript function from flash
Here is the code I have so far - Im prob doing something stupid
Flash:
ExternalInterface.addCallback( "myExternalMethod", this, myFunction );
function myFunction(){
gotoAndPlay("fade");
}
Javascript
function executeFlash()
{
getObjectById("myFlashID").myExternalMethod();
}
function getObjectById(objectIdStr) {
var r = null;
var o = document.getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != undefined) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
$(function() {
$('#WhatDoesmean').click(function(){
executeFlash();
});
});
I have set myFlashID to the id of:
initial 'Object tag'
and IE only 'embed tag'
EDIT:
At the moment I am targeting the flash object fine, it's the external (flash side) function which is not working
- error message, myExternalMethod is not a function
You can use the external interface for this:
There is a working example at this location:
Flash to JS:
http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001655.html
JS to Flash:
http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001653.html
Hope this helps
Cheers
I used this a few years ago to capture the flash object:
var flashObj = getFlash("Flash_Name");
function getFlash(movieName)
{
if (window.document[movieName])
{
return (window.document[movieName]);
}
if (navigator.appName.indexOf("Microsoft Internet")==-1)
{
if (document.embeds && document.embeds[movieName])
{
return (document.embeds[movieName]);
}
}
else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
{
return (document.getElementById(movieName));
}
}
Then a flashObj.gotoAndPlay(); should work
In your flash file add a callback:
//**updated**
if (ExternalInterface.available)
{
trace("ExternalInterface= " + ExternalInterface.available);
flash.external.ExternalInterface.addCallback("myExternalMethod", null, myFunction);
}
function myFunction()
{
gotoAndPlay("myLabel");
}
In your javascript:
function executeFlash()
{
//**updated**
alert('JS call works fine!');
getObjectById("myFlashID").myExternalMethod(); // myFlashID = your SWF object ID
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
In your HTML (give your SWF object embedded in your HTML an id = myFlashID):
<a href="" id="flashTrigger" onclick="executeFlash()" />
Here is where you find the documentation for ExternalInterface http://flash-reference.icod.de/
I have managed to crack the problem by using SWFObject
Accessign the flash objects method was easy through SWFObject.js, however it just wasnt working without it. Not sure why though.
All the above suggestions work with SWFObject.js, but none seemed to work without it
Cheers for everyones suggestions
Andy

Categories

Resources