I am running a small jquery code to my web page:
<!-- myjs.js -->
<script type="text/javascript">
$(document).ready(function() {
$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');
</script>
as you can see i am adding a div at my html body with specific class and id name.
How is it possible to execute this .js file throught actionscript 3.0?
I mean to make a flash movie and call this file, or is it possible to execute inline javascript code through AS 3.0?
I found the code bellow but i cant make it work:
import flash.external.ExternalInterface;
var someVarInAS : String = 'foo';
var someOtherVarInAS : int = 10;
var jsXML : XML =
<script type="text/javascript">
var someVarInJS = '{$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');}';
var someOtherVarInJS = '{$('#ajaxBusy).fadeIn();}';
<![CDATA[
alert( 'this comes from flash: ' + someVarInJS + ', ' + someOtherVarInJS );
]]>
</script>;
ExternalInterface.call( "function js_" + ( new Date().getTime() ) + "(){ " + jsXML + " }" );
I use this for loading JS files dynamically from AS3 and it works pretty well. Could be modified to run normal js rather than load another file:
var script:String = "" +
"var newscript = document.createElement('script');" +
"newscript.type = 'text/javascript';" +
"newscript.async = true;" +
"newscript.src = 'SomeJavascriptFile.js';" +
"(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);";
if ( ExternalInterface.available ) {
ExternalInterface.call("eval", script);
}
You could also avoid having to write javascript within actionscript and keep the two separate in their separate spots. Then just call the method name only using ExternalInterface, instead of calling 'eval' and passing in your javascript. It may be easier to test and maintain down the road.
Inside your html file:
<script>
function addDiv(){
// stuff here that adds the div you want, such as what you had:
$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');
}
</script>
Then inside flash:
if (ExternalInterface.available == true) {
ExternalInterface.call("addDiv");
}
You can also supply method arguments from flash to javascript if needed as well.
Related
First, I am not a programmer anymore... It's been years since doing it and even then it was only VBA and old school HTML.
What I would like to do is to show an image on my site in place of another depending on it's "state". For example, the site is http://w2zxl.hevener.com/ , towards the bottom of the page is a script that loads a HAM radio logbook as well as my current status in nearly real time. If I am on the Air, it will show a small image that says "On Air" and then show what frequency I am on and the Mode I am working in. When I am off the air however, that little image just disappears and shows nothing.
What I would like to do is to create a small image to replace the "nothing". In other words, if I am Off Air, I would like to show an "Off Air" image instead of nothing at all.
Is there an If/Then/Else statement that can do this given the code I am providing below?
Code below:
<!-- HRDLOG.net script start --><center>
<div id="hrdlog-oa"> </div>
<div id="hrdlog">www.hrdlog.net</div>
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
<script type="text/javascript" language="javascript">// <![CDATA[
var ohrdlog = new HrdLog('W2ZXL');
setInterval('ohrdlog.LoadOnAir()', 5000);
ohrdlog.LoadLastQso(10);
// ]]></script>
<img src="http://www.hrdlog.net/callplate.aspx?user=W2ZXL" alt="W2ZXL CallPlate" /></center><!-- HRDLOG.net script stop -->
Consider swapping CSS classes to change the background-image instead. This will simplify the javascript and html markup. When you're on air change the class to onair and toggle as needed to offair.
CSS
.onair {
background-image: url("onair.jpg");
}
.offair {
background-image: url("offair.jpg");
}
Html
<div id="hrdlog-oa" class="offair"></div>
Javascript
var statusDiv = document.getElementById("hrdlog-oa");
if (statusDiv.className == "offair") {
statusDiv.className = "onair";
}
else {
statusDiv.className = "offair";
}
Working jsfiddle http://jsfiddle.net/jasenhk/qMAZU/ using background-color instead.
You can not do that with pure HTML and you had 2 way for solving this
If you like markup languages you can use xsl that have if else tag for you
Using Javascript and check if you be on air show on air image and if you not be shows off air
for you the better way is change some javascript code in your site..
you should overwrite ohrdlog.LoadOnAir then you have two way again:
change http://www.hrdlog.net/hrdlog.js source code and rewrite LoadOnAir function
overwrite LoadOnAir function with inserting script tag after load http://www.hrdlog.net/hrdlog.js
i choose number 2 for you because i think you can`t change script that you load it from another domain address... now you should insert this code after this part:
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
and you can found link of offair image in HrdLog.prototype.ShowOffAir function that now, i point it to http://2.bp.blogspot.com/_Dr3YNV7OXvw/TGNNf561yQI/AAAAAAAABIk/-E2MB4jLP_o/s400/Off-Air.jpg:
<script type="text/javascript" language="javascript">
HrdLog.prototype.ShowOffAir = function() {
return '[<img src="https://i.stack.imgur.com/WEr1B.jpg" height="33" width="65" />][2]';
}
HrdLog.prototype.LoadOnAir = function() {
var t = this;
var async = new Async();
async.complete = function(status, statusText, responseText, responseXML, obj) {
if (status == 200) {
txt = '';
var xmldoc = responseXML;
var onairdoc = xmldoc.getElementsByTagName('OnAir');
if (onairdoc.length == 1) {
onair = onairdoc.item(0);
if (onair.getElementsByTagName('oa_QRZ').length > 0) {
txt += '<img src="http://www.hrdlog.net/images/onair.gif" height="33" width="65" /><br/>';
txt += '<font size="+1">' + onair.getElementsByTagName('oa_QRZ')[0].childNodes[0].nodeValue + ' is on air</font><br/>';
txt += '<b>';
txt += FormatNumber(onair.getElementsByTagName('oa_Frequency')[0].childNodes[0].nodeValue) + ' ';
try {
txt += onair.getElementsByTagName('oa_Mode')[0].childNodes[0].nodeValue + '</b><br/>';
txt += onair.getElementsByTagName('oa_Radio')[0].childNodes[0].nodeValue + '<br/><br/>';
} catch (e) { }
//txt += onair.getElementsByTagName('oa_Status')[0].childNodes[0].nodeValue + '<br/>';
}else{
txt += t.ShowOffAir();
}
}else{
txt += t.ShowOffAir();
}
element = document.getElementById('hrdlog-oa');
if (element != null) {
element.innerHTML = txt;
}
} else {
alert('Error\n' + statusText);
}
}
if ((new Date().getTime() - this._lastLoadOnAir.getTime()) > 14500) {
this._lastLoadOnAir = new Date();
async.req(this._host + 'hrdlog.aspx?onair=' + this._qrz, this);
}
}
</script>
I have this form:
<form id="searchForm" class="search_field" method="get" action="">
...
...
</form>
Then this javascript:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
form.showFeatureChoices.onclick = function( )
{
var cbs = form.featType;
for ( var c = 0; c < cbs.length; ++c )
{
cbs[c].checked = false;
}
document.getElementById("featuresDiv").style.display = "block";
}
function searchPage()
{
var form = document.getElementById("searchForm");
var searchText = form.searchBox.value.replace(/-/g,"");
form.searchBox.value = searchText;
if (searchText != "")
{
// collect features to search for:
var features = [ ];
var featTypes = form.featType;
for ( var f = 0; f < featTypes.length; ++f )
{
if ( featTypes[f].checked ) features.push( featTypes[f].value );
}
featureList = "'" + features.join("','") + "'";
searchMsg("Searching for '" + searchText + "' ...");
// startStatusUpdate(1000);
// findTask.execute(findParams, showResults);
var accord = dijit.byId("accordianContainer");
var resultsPane = dijit.byId("resultsPane");
accord.selectChild(resultsPane,true);
doSearch( searchText, featureList );
}
else
{
searchMsg("No search criteria entered, enter search text");
}
}
If I embed this code in same file as the <form..., it works fine.
If however, I have this js in another file and use as include file:
<script type="text/javascript" src="Views/JS/main.js"></script>
I get following error: "Object required" and it points to these lines:
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
Any ideas how to fix this?
Just a bit more info, the js code shown above in a file called main.js which is in a folder called JS and Js is in a folder called Views. The
Thanks a lot in advance
When you include the JavaScript code in the same page, where is it in relation to the form element? (Before or after it?) How about when you reference the external JavaScript file?
I'm guessing that in the former case the code is at the end of the file, while in the latter case the script reference tag is at the beginning?
If that's true then what's happening is this code is being executed before the DOM is ready:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
If the form tag hasn't been rendered to the DOM yet then that first line won't find anything, and the subsequent lines will fail as a result. One approach is to put the script reference tags at the end, but that seems like a hack to me. Sometimes there are good reasons to keep them in the page header, not the least of which is cleaner management of the code in many cases. There are other ways to hold off on executing JavaScript code until the DOM is ready.
I wrote a small RSS reader with JQuery. At first theres a screen with the titles of the articles, when clicked on a title I load the content of that article. The problem is, it contains some google ads script, which will replace the content of the article and fill the whole screen with an advertisement.
The following script is what I am tying to replace or ignore:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-8356817984200457";
/* ijsselmondenieuws.nl */
google_ad_slot = "9061178822";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
So I wrote a method which is supposed to remove the script by a simple replace:
var replaceScript='<script type="text/javascript"><!--\n' +
'google_ad_client = "ca-pub-8356817984200457";\n' +
'/* ijsselmondenieuws.nl */\n' +
'google_ad_slot = "9061178822";\n' +
'google_ad_width = 468;\n' +
'google_ad_height = 60;\n' +
'//-->\n' +
'</script>\n' +
'<script type="text/javascript"\n' +
'src="http://pagead2.googlesyndication.com/pagead/show_ads.js">\n' +
'</script>';
function removeADS(ads) {
removeAD = ads.replace(replaceScript, " ");
}
But this doesn't work, I think it's not flexible either (if it would work). When something changes in the script, the application will get stuck at the advertisement again. Is there some way to completely ignore this script while fetching the content from an RSS feed or a more flexible replacement script?
Any help is appreciated,
Thanks!
It's not very wise to parse xml/html with regex.
Use a dom parser (jquery is a beautiful one ...hint hint):
var rssContentString = '<rss version='2.0'>...',
xmlDoc = $.parseXml(rssContentString),
$xml = $(xmlDoc),
helper = $('<div />'),
result;
result = helper
.append(
$xml
.find('script')
.remove()
.end()
)
.text();
UPDATE
Based on the new comments, since you get your rss content like this :
content:$.trim($(v).find("content").text())
you can modify this expression to the following :
content:$.trim($(v).find("content").find('script').remove().end().text())
I have some JS from an external JS file that I want to insert inside of a JS function in the HTML file. I can not touch the JS script in the HTML file, so I am wondering if this method can be done.
Here is the JS I want to insert inside of the JS function in the HTML file.
// FIRST JS TO INSERT
if (OS == "mobile"){
killVideoPlayer();
}
// SECOND JS TO INSERT
if (OS == "mobile"){
loadHtmlFiveVideo();
if (!document.all){
flvPlayerLoaded = false;
}
}else {
loadVideoPlayer();
}
Then I want to insert it into here.
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
// INSERT FIRST JS HERE
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("frame_photo").style.display = "none";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "none";
// INSTER SECOND JS HERE
loadVideoPlayer();
}
if (bsiCompleteArray[arrayIndex].mediaType == "photo") {
killVideoPlayer();
document.getElementById("bsi-video-wrap").style.display = "none";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("frame_photo").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "block";
if (!document.all){
flvPlayerLoaded = false;
}
}
}
</script>
Thank you!
In JavaScript, you can overwrite variables with new values at any time, including functions.
By the looks of it, you could replace the mediaTypeCheck function with one of your own that does what you need and then calls the original function.
E.g.
(function(){
// keep track of the original mediaTypeCheck
var old_function = mediaTypeCheck;
// overwrite mediaTypeCheck with your wrapper function
mediaTypeCheck = function() {
if ( conditions ) {
// do whatever you need to, then ...
}
return old_function();
};
})();
The above can be loaded from any script, so long as it happens after the mediaTypeCheck function is defined.
The easiest way for me in the past has been using server-side includes. Depending on your back end, you can set up a PHP or ASP page or whatever to respond with a mime type that mimics ".js".
I'm not a PHP guy, but you'd do something like this: (if my syntax is incorrect, please someone else fix it)
<?php
//adding this header will make your browser think that this is a real .js page
header( 'Content-Type: application/javascript' );
?>
//your normal javascript here
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
//here is where you would 'include' your first javascript page
<?php
require_once(dirname(__FILE__) . "/file.php");
?>
//now continue on with your normal javascript code
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
.......
You cannot insert JS inside JS. What you can do is insert another tag into the DOM and specify the SRC for the external JS file.
You can directly insert js file using $.getScript(url);
if you have script as text then you can create script tag.
var script = docuent.createElement('script');
script.innerText = text;
document.getElementsByTagName('head')[0].appendChild(script);
The issue in your case is that you cannot touch the script in the html, so I'll say that it cannot be done on the client side.
If you could at least touch the script tag (not the script itself), then you could add a custom type to manipulate it before it executes, for example:
<script type="WaitForInsert">
Your question looks some strange, but seems to be possible. Try my quick/dirty working code and implement your own situation:
$(document.body).ready(function loadBody(){
var testStr = test.toString();
var indexAcc = testStr.indexOf("{");
var part1 = testStr.substr(0, indexAcc + 1);
var part2 = testStr.substr(indexAcc + 1, testStr.length - indexAcc - 2);
var split = part2.split(";");
split.pop();
split.splice(0,0, "alert('a')");
split.splice(split.length -1, 0, "alert('d')");
var newStr = part1 + split.join(";") + ";" + "}";
$.globalEval(newStr);
test();
}
function test(){
alert('b');
alert('c');
alert('e');
}
I'm building an advert delivery method and am try to do it through an external Javascript/jQuery page.
I have this so far, but I have some issues with it
$.get('http://url.com/ad.php', {
f_id: _f_id,
f_height: _f_height,
veloxads_width: _f_width
}, function (result) {
var parts = result.split(",");
var path = parts[0],
url = parts[1];
document.write('<img src="' + path + '">');
I can see the page load, but then after the code above is loaded, it creates a new page with just the advert on it. Is there anyway I can write it onto the page where the code was put?
And this is the script web masters put on their websites to include the adverts:
<script type="text/javascript">
var _f_id = "VA-SQ2TDEXO78N0";
var _f_width = 728;
var _f_height = 90;
</script>
<script type="text/javascript" src="http://website.com/cdn/addelivery.js"></script>
Cheers
is ad.php on the same domain as your script? if it's not have a look at this article
here is a code you could use in your html page, where you want the ad to be inserted:
$.get('http://url.com/ad.php',
{ f_id : _f_id, f_height : _f_height, veloxads_width : _f_width }
).success(function(result) {
var parts = result.split(",");
var path = parts[0], url = parts[1];
$('body').prepend('<div id="ad_id"><img src="'+path+'"></div>');
});
the selector (body here) can be an id, a class, ... (see documentation). You can also use prepend() or html() instead of append, to insert the code where you want ;)