ExternalInterface and Javascript not working in harmony - javascript

The other day I posted about a Flash/Javascript issue I was having. Please see this:
Issues with javascript properly loading and seeing everything
I know how I want to fix it, but I am not in any way shape or form familiar with actionscript. I have avoided adobe products like the plague from when I was developing myself since it costs a fortune to buy and of their products, but big employers love it and pay for it so here I am. Our "Flash" guy just left the team and I inherited this issue. If you read my other post you know what is going on so I will move on. I want to make a simple call from actionscript to my javascript taht is referenced in my other post. I specifically want to call the CheckboxCollection function from inside of actionscript. I don't need to pass it any args or anything of the such from inside of actionscript. All I need it to do is run that function once the flash is done loading. The javascript function will take care of everything I need, I just HAVE TO HAVE IT called from actionscript to make everything work in harmony. I am in the middle of teaching myself all things adobe and actionscript(much to my dismay), but I really have no clue where top go from here to make this work. I have reviewed adobe documentation, but until I have a better grasp of the language as a whole I am still lost. I copied most of my actionscript on to here, but I did leave out everything that had to deal with mouseover events, since my issue is not about a mouseover and they all work like a charm. Thanks in advance!
-------------------------------------------------------------------------------------------UPDATE: I had to stop working on this to get some other things done, but I am back to step one. NO matter what I do I am having no luck making this work. I have tried all suggestions on here, and tried everything I KNOW how to do, but I am having no luck. If anyone could take a look at this post and the one that I link to (It is the companion javascript for this) and see if they can come up with anything. I have tried so many different iterations of my code there is no use putting all of my trials up for example of what doesn't work, Thanks Everyone!
/*
JavaScript External Calls
*/
function RegisterExternalCalls():void
{
if(ExternalInterface.available)
ExternalInterface.addCallback("HighlightWheel", HighlightWheel);
}
function HighlightWheel($args:String,$show:String,...arguments):void
{
$args = $args == "financial"?"center":$args;
var _obj:Object = ObjectCollection[$args].Objects.Click;
if(ObjectCollection[$args].Objects.currentObject.name.toLowerCase() == "center")
{
bcenter = true;
_obj = ObjectCollection[$args].Objects.currentObject.getChildByName("financialBtn");
}
if(CBool($show))
{
if(arguments.length > 0 && arguments[0] == "TITLE") // || $args == "center")
_obj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER));
else
{
if(ObjectCollection[$args].labels.Label.toUpperCase() === "CENTER")
{
ObjectCollection["income"].Objects.Click.gotoAndPlay(2);
ObjectCollection["property"].Objects.Click.gotoAndPlay(2);
ObjectCollection["education"].Objects.Click.gotoAndPlay(2);
ObjectCollection["health"].Objects.Click.gotoAndPlay(2);
ObjectCollection["retirement"].Objects.Click.gotoAndPlay(2);
}
else
{
_obj.gotoAndPlay(2);
}
}
}
else
{
if(arguments.length > 0 && arguments[0] == "TITLE")
_obj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT));
else
{
if(ObjectCollection[$args].labels.Label.toUpperCase() === "CENTER")
{
ObjectCollection["income"].Objects.Click.gotoAndPlay(11);
ObjectCollection["property"].Objects.Click.gotoAndPlay(11);
ObjectCollection["education"].Objects.Click.gotoAndPlay(11);
ObjectCollection["health"].Objects.Click.gotoAndPlay(11);
ObjectCollection["retirement"].Objects.Click.gotoAndPlay(11);
}
else
{
_obj.gotoAndPlay(11);
}
}
}
}
function CallExternalFunction($label:String,$show:Boolean = true):void
{
var lbl:String = $label.toLowerCase().indexOf("btn") > -1?"financialTitle":$label + "Title";
if(ExternalInterface.available)
ExternalInterface.call("COUNTRY.Financial.highlightProductGroup",lbl,$show);
}
function CBool($value:String):Boolean
{
if($value == "true")
return true;
else
return false;
}
function PrintSetup($evt:MouseEvent):void
{
var pjob:PrintJob = new PrintJob();
if(pjob.start())
{
pjob.addPage(wheel);
pjob.send();
}
}

I believe you do this through ExternalInterface.call and pass the javascript function that should be called, like so:
ExternalInterface.call( "CheckboxCollection" )
If you need to pass arguments:
ExternalInterface.call( "CheckboxCollection", value1, value2 )
For more information here is the documentation

If in your JS you don't need necessarily this:
var CheckboxCollection = function()
try to change it to this:
function CheckboxCollection()
even if it seems (if the JS is still the same) you have anything nested. Maybe you can try too call it this way to (but I never tried anything similar):
ExternalInterface.call("SOME.PLACE.QuoteRequest.CheckboxCollection");

Related

Javascript .focus() not working

I'm having trouble getting the javascript .focus() function to work. At this point, I'm really not sure why it's failing to execute. Could it have something to do with onload?
This is my code:
var request_brochure = function()
{
var name = $("name").value;
var email = $("email").value;
var isValid = true;
if(name == "")
{
$("name").focus();
alert("Please fill in your name.");
$("name").focus();
isValid = false;
}
else if(email == "")
{
window.setTimeout(function(){$("email").focus();}, 100);
alert("Please fill in your email. ");
window.setTimeout(function(){$("email").focus();}, 100);
isValid = false;
}
if(isValid)
{
$("form_b").submit();
//$("brochure").innerHTML = "Request Submitted";
}
}
window.onload = function () {
$("name").focus();
$("submit1").onclick = request_brochure;
}
var $ = function (id) {
return document.getElementById(id);
}
Any help is appreciated
I suspect the event isn't binding correctly. window.onload does not ensure the element with id submit_1 is loaded. try adding the event to the button directly:
<input id="submit_1" onclick="request_brochure()" />
if that works then your problem is just that. Without jQuery you could mostly get away with binding the event by putting $("submit1").onclick = request_brochure; in a <script> at the end of the page, but results will be mixed from browser to browser. I'd really recommend using jQuery(function () { $("submit1").onclick = request_brochure; }) and leaving the heavy lifting of determining when the page is completely loaded to the library, since it's been tried and tested for years and is much less likely to fail than a native approach.
The comments on your question have a lot of truth, and I'd hate to see you go down the path of jQuery's high level stuff designed to make non-programmers and programmers with little javascript knowledge live's easier. With that said, the browser landscape is quite the jungle, with more than half of the world on IE 8 or lower (I could be wrong about that by now, but I'm sure it's still a considerable amount), jQuery's low level stuff (like $.ajax, $(function () {}) and the sizzle selector engine) is indispensable in my opinion. The main purposes of these utilities (jQuery's low level functions) is to address browser fragmentation issues and make devs live's easier. It's good to know the underlying code, but I'll take $.ajax over any implementation of HttpXmlRequest in a heartbeat (I still remember the days of IE6's activeX component... those were dark times). just don't do $('#some-form-field').val() without first learning document.getElementById('some-form-field').value and you should be fine :)

RaphaelJS animate does not work when called from an outside method

As a desktop developer I am very new to Javascript, so I often run into things that puzzle me about the language. I was working with click events on RaphaelJS shapes, and initially I was setting the state and animation of the object in a private method:
innershape.node.onclick = function () {
if (scope.state === 0) {
_setState(1);
} else {
_setState(0);
}
};
function _setState(state) {
scope.state = state;
if (scope.state === 0) {
innershape.animate({ fill: "#00FF19" }, 500);
} else {
innershape.animate({ fill: "#C05219" }, 500);
}
}
This was functioning as expected. I then decided to add an outside function that would loop through all the objects and de-select (and therefore reverse-animate) all the other shapes. The result may be seen in this jsfiddle: http://jsfiddle.net/txj4zasn/4/
The function is called properly, and the animate() function is apparently executed, but the visible animation never appears, and the color never changes. I suspect that this is something very basic to Javascript that I just don't understand. Can someone explain to me why this is happening?
Its not really very clear what you want to achieve (beyond getting the animation to work), so my initial solution I think isn't good, but I will expand on that.
The problem looks a bit like you are trying to combine two different elements, functional scope and object variables.
A quick solution would be to include...
this.id = 1;
var id = this.id; // so id now a closure to the later function
as updateSelected(id); the id here, is inside another function, so we can't use 'this.id'. But then later you are checking against z[i].id so you need that to be defined also.
jsfiddle
This all feels a bit clunky though, prone to error, and is quite hard to read. So the first question is do you need objects ? You could store information in the "data" part of a Raph element, which already is an object.
Here is an example of how I would write it, I appreciate this may not be suitable as it may be part of a bigger project which needs other elements in an object, but it may give some idea.
function updateSelected( el ) {
if( el.data('innerstate') == 1 ) {
el.animate({ fill: "#00FF19" }, 500);
el.data('innerstate',0)
} else {
el.animate({ fill: "#C05219" }, 500);
el.data('innerstate',1);
}
}
function addElement() {
var innershape = paper.rect(100,100,100, 100);
innershape.attr({fill: "#00FF19" });
innershape.data('innerstate', 0);
innershape.click( function () {
updateSelected( innershape )
} );
};
addElement();
This code I can pretty much read instantly and know how and if it will work.
jsfiddle
jsfiddle showing it combined with more than one element, or jsfiddle thats a bit more compact

Javascript function that should return a function becomes the function

Long ago I've read a lot about javascript coding conventions, and one of the things I wanted to decide was the better way of declaring functions. I finally somehow stuck with the
var func_name = function(){};
version, because it seemed more useful in certain scenarios, but I wasn't really able to find things that wouldn't work the same way between them until now.
I was writing a function that should've returned a new function to be used in a setTimeout command, but I couldn't get it to work properly, and after I reduced the whole thing to this test code:
var test = new function(x) {
return function() {
if (x % 2 == 1) {
console.log('a');
}
else {
console.log('b');
}
x++;
};
};
I happened to try if writing it in the
function func_name(){}
style would help (because I really couldn't see the problem with my code), and interestingly enough this code
function test(x) {
return function() {
if (x % 2 == 1) {
console.log('a');
}
else {
console.log('b');
}
x++;
};
}
seems to be working perfectly.
A weird thing to discover was that after playing a bit around in the console I realized that the first one effectively becomes the function it should generate.
I tested it in Chrome and Firefox too, and I also tried using it this way
var test = new function(x) {
var result = function() {
if (x % 2 == 1) {
console.log('a');
}
else {
console.log('b');
}
x++;
};
return result;
};
but I wasn't able to make it work.
I would be interested in any explanation to this phenomenon and also it fascinates me if there is a way to make this type of function declaration capable of producing functions.
Thanks in advance!
Edit: I don't know how, but somehow that new keyword got there by mistake :D (and even into the third version by that stupid copy-paste laziness of mine.....)
I'm still interested in knowing why the function becomes what it should create though!
Why are you using new? Remove that and it should be fine IMO.
You are using it as if it were a Construtor.
Though valid, can create issues as your current issue.

JavaScript Event Not Firing

So I recently decided to start learning JavaScript. I come from only knowing VB.NET for programming knowledge and HTML & CSS for design. Anyway, scrap.tf is a website for TF2 banking which makes things automatic. I am planning to write a basic Chrome plugin, and I want to be able to if the button is clicked, this function will happen. I've got this all set up but when the button's clicked, it only takes me to scrap.tf/hats, EnQueueHatBank(); is the JS command they use there to join the queue. This even never fires unless I type it in after I'm on the site. Do I need to wait for it to fire?
if (location.href === 'http://scrap.tf/hats')
{
EnQueueHatBank();
}
else
{
window.location.href='http://scrap.tf/hats';
EnQueueHatBank();
}
You need to correct the comparison to use two equal signs.
if (location.href == 'http://www.scrap.tf/hats')
{
EnQueueHatBank();
}
Once you end up with tools like jslint, javascript even offers a === operator, which does type checking, too (checks if both sides are strings, as in this example).
I think this talk of = vs == is missing the point. You're changing window.location before you call EnQueueHatBank, so you navigate to a new page before the function is ever called. That's what's stopping it from running. So the first thing you need to do is:
Call EnQueueHatBank first.
if (location.href === 'http://www.scrap.tf/hats') {
EnQueueHatBank();
} else {
EnQueueHatBank();
window.location.href='http://www.scrap.tf/hats';
}
Clean up the code a little, because the structure is a little awkward. You're calling EnQueueHatBank either way, so there's no need for it to be in the if statement:
EnQueueHatBank();
if (window.location.href !== 'http://www.scrap.tf/hats') {
window.location.href = 'http://www.scrap.tf/hats';
}
Finally, remember that http://www.scrap.tf/hats/ probably goes to the same place as http://www.scrap.tf/hats, not to mention https://www.scrap.tf/hats?foo=bar and so forth. You'd be better off with a less-strict test:
EnQueueHatBank();
if (window.location.href.indexOf('://www.scrap.tf/hats') > -1) {
window.location.href = 'http://www.scrap.tf/hats';
}
EDIT: Based on your comment, you will need to do this:
if (window.location.href.indexOf('://www.scrap.tf/hats') > -1) {
EnQueueHatBank();
}
else {
window.location.href = 'http://www.scrap.tf/hats';
}
This will only work if your program runs again after navigating to scrap.tf/hats, so make sure it runs every time you load a new page.
For security reasons, you cannot initiate code on one page and have it continue after you've navigated somewhere else. You'll have to call EnQueueHatBank from the page it's meant to run on.
You should use comparison === operation, but you did an value assignment =.
if (location.href === 'http://www.scrap.tf/hats')
{
EnQueueHatBank();
}
else
{
window.location.href='http://www.scrap.tf/hats';
EnQueueHatBank();
}

if/else statement in a function: using onclick as a switch

I have looked for solutions to this on google for what seems like an eternity, but I can't seem to formulate my search correctly, or nobody has posted the code I'm looking for earlier.
I am currently trying to make a function that will modify one or several margins of a div element. I want to use an if/else statement within the function, so that the onclick event will switch between the two conditions. This is what I have been working on so far;
function facebookToggle()
{
if($('#facebooktab').style.margin-left == "-250px";)
{
document.getElementById("facebooktab").style.marginLeft="0px";
}
else
{
document.getElementById("facebooktab").style.marginLeft="-250px";
}
}
I have tried twisting it around a little, like switching between "marginLeft" and "margin-left", to see if I was just using the wrong terms.. I'm starting to wonder if it might not be possible to combine jQuery and regular javascript? I don't know.. It's all just guesses on my part at this point.
Anyway, I have a div, which is now positioned (fixed) so almost all of it is hidden outside the borders of the browser. I want the margin to change onclick so that it will be fully shown on the page. And when it is shown, I want to be able to hide it again by clicking it.
I might be approaching this in the wrong way, but I really hope someone can help me out, or even tell me another way to get the same results. Thank you for any help you can give me.
You can see it in action at: http://www.torucon.no/test/
(EDIT: By the way, I am a complete javascript novice, I have no experience with javascript prior to this experiment. Please don't be too harsh, as I am aware I probably made some really stupid mistakes in this short code.)
Fixed problem:
function facebookToggle() {
var fb = $('#facebooktab'); // save reference to element
if( fb.css('margin-left') === '-250px' ) {
fb.css('margin-left', '0px');
} else {
fb.css('margin-left', '-250px');
}
}
A jQuery object doesn't have a property called style, so
if($('#facebooktab').style.margin-left == "-250px";)
// also remove this semi-colon! ^
is going to throw an error. Some options for accessing CSS properties are (1)
document.getElementById("facebooktab").style.marginLeft;
which you have correctly used, or (2)
$('#facebooktab').css('margin-left');
Consider being consistent and using the same approach for all three cases. You can assign css properties with jQuery like
$('#facebooktab').css('margin-left', '-250px');
With these things in mind, here's a suggested rewrite:
function facebookToggle() {
var fb = $('#facebooktab'); // save reference to element
if( fb.css('margin-left') === '-250px' ) {
fb.css('margin-left', '0px');
} else {
fb.css('margin-left', '-250px');
}
}
and here's another that uses a predefined CSS class:
#facebooktab {
margin-left: -250px; /** default state */
}
.no-left-margin {
margin-left: 0px;
}
function facebookToggle() {
$('#facebooktab').toggleClass('no-left-margin');
}
toggleClass
jQuery is just a JavaScript library. It is written in JavaScript and its API is in JavaScript. Your event handler could be rewritten as follows:
function facebookToggle() {
var el = document.getElementById('facebooktab');
if (el)
el.style.marginLeft = (el.style.marginLeft == '250px' ? 0 : -250) + 'px';
}
Since you are mixing jQuery with javascript, you got mixed up. Apart from what paislee's advice. you are do this too.
if($('#facebooktab')[0].style.margin-left == "-250px";){
document.getElementById("facebooktab").style.marginLeft="0px";
}
else {
var fb = document.getElementById("facebooktab");
fb.style.marginLeft="-250px";
}

Categories

Resources