Pass a Parameter to Another Function and Into innerHTML - javascript

I've built my own lightbox, and it's working rather well. I built my own because I needed it to be without a framework, and also work well within a game I'm building. However, I've run into a problem I'm fairly certain is simple, but proving rather vexing to me. The issue I'm having is taking the parameter "slideName" and passing it through to the "fillRightButton()" function.
var createSlidebox = function(cancelButton, bannerImg, slideName) {
fillRightButton("nextSlide",slideName);
};
Here's a portion of that function:
var fillRightButton = function(rightButtonType, rightDestination) {
if (rightButtonType === "nextSlide") {
document.getElementById("lightbox_fright").innerHTML = '<a onclick="changeSlide(' + rightDestination + ')">Next</a>';
}
}
The "fillRightButton()" function performs fine when it is called directly, and this code works if you put the parameter in directly:
var createSlidebox = function(cancelButton, bannerImg, slideName) {
fillRightButton("nextSlide", "mySlideName");
};
However, without the quotes it renders as:
<a onclick="changeSlide([object Object])">Next</a>
with a "Uncaught SyntaxError: Unexpected identifier" JS error. How would I fix this? Thanks!

use data attribute to store the object using jQuery, in function call
var fillRightButton = function(rightButtonType, rightDestination) {
if (rightButtonType === "nextSlide") {
document.getElementById("lightbox_fright").innerHTML = '';
// document.getElementById("lightbox_fright").innerHTML = '<a onclick="changeSlide( $(this).data('dest') )">Next</a>';
var a = document.createElement('a');
a['data-dest'] = rightDestination;
a.onclick=function(){changeSlide( this['data-dest']); }
a.innerHTML = 'Next';
document.getElementById("lightbox_fright").appendChild(a);
//document.getElementById('lightbox_fright > a').data({'dest':rightDestination});
}
}
use jQuery if not already included
PS updated w/o jQuery please give it a try let me know if it works, recommend using jQuery though

Related

How to use Teaspoon for JS testing

I'm new to JS testing and I would like to understand how to test a JS function I have. I'm using Teaspoon-mocha as the testing library and the function I would like to test is:
var C_FORM = "http://www.exmple.com/SomeForm#Form";
function getNamespace(uri) {
var parts = uri.split("#");
if (parts.length == 2) {
return parts[0];
} else {
return "";
}
}
I would like to have an example how to test this specific function.
This function actually getNamespace from the final part of a specific URI which is defined by that var C_FORM so the result is that is getting the namespace which is Form.
I would like to test this function if it is doing this by Teaspoon but as above I'm not familiar with this kind of testing, I need just an example to get familiar.
I tried the next solution but I get that equal is undefined:
describe("Application", function() {
it("Gets Namespace", function() {
var uri = "http://www.test.com/SomeTest#Test";
expect(getNamespace(uri).to.equal("http://www.test.com/SomeTest"))
})
});
Please try this way:
expect(getNamespace(uri)).to.equal("http://www.test.com/SomeTest")

Java Script Function is not Defined JSP Error

I keep getting "function is not defined" errors while working on a Javascript/HTML page.
EDIT: Updated Link: http://jsfiddle.net/Gmyag/134/
EDIT: Updated link http://puu.sh/8CxnC/b954c1c803.html is the actual one I'm working with and would likely prove leagues more useful than the fiddle.
HTML:
deliveryIdentification is the one giving issues. Code too long.
Had to add code block since I added a jsfiddle.
Sorry for not simplifying the example, but this is the first time I've seen this.
If I put everything on a separate script blocks others seem to work, but with the addDelRefOrder() since I need to declare var deliveryDummy[] before it throws "ReferenceError: deliveryDummy is not defined. And if I put deliveryDummy[] in the same block it says "ReferenceError:addDelRefOrder() is not defined".
As to why the structure is so weird it's due to it being a .jsp file. I'm just starting out with JSP and learning a lot along the way.
Any and all help as of how to fix this issue is greatly appreciated.
You are defining function inside function ? Here
function renderList()
{
// clean the list:
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Recreate li
for(var i = 0; i < deliveryDummy.length; i++) {
var entry = document.createElement("li");
entry.appendChild(document.createTextNode(deliveryDummy[i]));
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Remove"));
removeButton.setAttribute('onClick','removeName('+i+')');
entry.appendChild(removeButton);
list.appendChild(entry);
}
function removeDeliver(deliverIndex){
deliverDummy.splice(deliverIndex,1);
// Array changed to re-render List
renderList();
}
function getDeliver() {
return deliverDummy;
}
}
you have renderList() and inside this two more funcs. This is the wrong structure for Javascript. Make separate functions.
I'm not very familiar with jsp either but your HTML tagging is a little messy.
Make sure that the html tags are properly nested.
in your javascript i noticed that you have made calls to functions before you have created them. first fix this issue and see if it resolves your problem.
window.onload=function addDelRefOrder()
{
var deliveryVal = document.getElementById("deliveryIdentification").value;
// Add to array
deliveryDummy.push(deliveryVal);
// Array changed, Re-Render
renderList(); /// <==== HERE
}
window.onload=function renderList() // <====== Function created here.
{
// clean the list:
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Recreate li
for(var i = 0; i < deliveryDummy.length; i++) {
var entry = document.createElement("li");
entry.appendChild(document.createTextNode(deliveryDummy[i]));
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Remove"));
removeButton.setAttribute('onClick','removeName('+i+')');
entry.appendChild(removeButton);
list.appendChild(entry);
}
}

how to build dynamic call to javascript function using asp.net mvc and knockoutjs

I am building a mvc aplication using as template HotTowel (you know, durandal, knockout, breeze,etc). The application is not ready yet we are doing good progress :).
At the middle of one funcionality I need to build a dynamic call to javascript function.
The call using hard code values is something like:
<a href="#" id="openreport"
onclick="showReport('#Url.Action("Index","Report", new { Id= 9, languageId = 2})');">Show
report</a>
The call abover works fine. My troubles start when i try using knockoutjs to bind onclick event to string property. something like this:
<a href="#" id="openReport" data-bind="onclick: $root.reportUrl()" >
Show report
where report url it's a obervable variable. here the typescript code:
export var reportUrl =<any> ko.observable();
export var expandRow = function (myObjectComeFromATable) {
var urlAction = '#Url.Action("Index", "Report", new { Id= ID_TO_REPLACE, languageId = LANG_TO_REPLACE }) ';
var url = "showReport('"+urlAction+"');";
reportUrl(url);
};
UPDATE
Use of quotes are fine. the value of the knockout variable is same has hard code value showed before. Maybe it's a aproblem with my sintaxis in the layout?
You are trying to eval code in an observable? I don't think it will work. You could do the eval manually in a function. But I don't think that's a good solution.
If you always call "showReport" on click, you don't need an eval: just have a property in your model that contains the url to call, and run showReport(yourUrl) in a callback function.
If the function you are calling on click changes, you could keep a reference to the function to call in your model. Something like that (but cleaner):
var model = function() {
var _this = this;
this.function1 = function() {
alert('hello');
}
this.function2 = function() {
alert('world');
}
this.run = function() {
_this.current();
}
this.change = function() {
_this.current = _this.function2;
}
this.current = this.function1;
}
ko.applyBindings(new model());
Click
Switch
See here: http://jsfiddle.net/pp2QA/2/

Create a string (text) that declares variable and its value, for use in Javascript

I am messing with Javascript code that needs to have variable dynamic part.
I am trying to substitute this piece of Javascript code:
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
with something like:
var encapsulatedData = "var data = document.getElementById('IDofSomeHiddenField').value;";
var encapsulatedPrint = "var print = document.getElementById('IDofOutputField');";
so that when I use somewhere in Javascript code:
encapsulatedData;
encapsulatedPrint;
this will work:
print.value = data;
But it does not work.
Is there a way how to declare:
var encapsulatedData
var encapsulatedPrint
in similar manner like I wrote above, so that:
print.value = data;
works?
Do you mean magically create global variables?
function encapsulatedData() {
window.data = document.getElementById('IDofSomeHiddenField').value;
}
function encapsulatedPrint() {
window.print = document.getElementById('IDofOutputField');
}
encapsulatedData();
encapsulatedPrint();
print.value = data;
This is not very sanitary code, and what you want is probably not what you should be doing. Could you step back and say what your goal is, rather than the means to that goal? I suspect what you really want to be using are closures or returning first-class functions for delayed evaluation.
For example:
function makePrinter(id) {
var outputfield = document.getElementById(id);
return function(value) {
outputfield.value = value;
}
}
function getValue(id) {
return document.getElementById('IDofSomeHiddenField').value;
}
var data = getValue('IDofOutputField');
var print = makePrinter('IDofOutputField');
print(data);
You have a syntax error I think. You're not closing the parentheses on the first and second lines.
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
It is also bad form to use JS evaluation like you're attempting to do. If anything you really want to create a function for each of the page elements that returns the page element. ECMAScript 5 has properties which I think is sort of what you're looking for with what you're trying to do but that isn't how ECMAScript 3 JS can work.

Flash player control from javascript outside?

I am making flash player that suppose to be controlled from outside, from javascript.
I need those methods:
Play/Pause and Volume level
I am stuck with volume level... I tried to add this code:
flashMovie.volume = 10;
Where flashMovie is flash instance... And it's show NO ERROR but it's NOT WORKING
I try to make inner AddCall(); and then when it's called to call() from javascript to return sound level.
AS 3:
function setthisvolume()
{
var vlm = ExternalInterface.call('giveMeVolume()');
this.soundTransform.volume = vlm;
}
ExternalInterface.addCallback("setthisvolume", setthisvolume);
JS:
var soundlevel = 10;
function soundlevelset()
{
var flashMovie=getFlashMovieObject("objswf");
flashMovie.setthisvolume();
}
function giveMeVolume()
{
return parseInt(soundlevel);
}
But I am getting this error:
Error calling method on NPObject!
I even tried with setInterval():
AS 3:
function setthisvolume()
{
var vlm = ExternalInterface.call('giveMeVolume()');
this.soundTransform.volume = vlm;
}
setInterval(setthisvolume, 1000);
JS:
var soundlevel = 10;
function giveMeVolume()
{
return parseInt(soundlevel);
}
And it doesn't show any error, but it doesn't work neither...
Did someone work with stuffs like this?
Can someone help me what I am doing wrong here...
Thank you!
Thank you, #someone!
This second option worked okay!
Here is working code:
AS3:
function setthisvolume(vlm)
{
this.soundTransform = new SoundTransform(vlm);
}
ExternalInterface.addCallback("setthisvolume", setthisvolume);
JS:
function getFlashMovieObject(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
{
return document.getElementById(movieName);
}
}
var soundlevel = 0.5; // it's 0-1 volume, not 0-100
function soundlevelset()
{
var flashMovie=getFlashMovieObject("objswf");
flashMovie.setthisvolume(parseFloat(soundlevel));
}
When you are using slider each time slider change you need to change soundlevel variable and call soundlevelset();
Hope I helped next one who is starting with this... :)
Thank you!
Try removing the parentheses when calling giveMeVolume, by changing this:
var vlm = ExternalInterface.call('giveMeVolume()');
to this:
var vlm = ExternalInterface.call('giveMeVolume');
If that doesn't work, try passing the volume directly as an argument/parameter, like this (this is probably a better way to do it):
AS3:
function setthisvolume(vlm)
{
this.soundTransform.volume = vlm;
}
ExternalInterface.addCallback("setthisvolume", setthisvolume);
JS:
var soundlevel = 10;
function soundlevelset()
{
var flashMovie=getFlashMovieObject("objswf");
flashMovie.setthisvolume(soundlevel);
}
Code looks reasonable.
Check if you allow Flash to communicate with script There is property when you create Flash object - AllowsScriptAccess - http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7c9b.html .
Check if Falsh is coming from the same domain as HTML page.
For addCallback check if you are getting correct Flash object by Id (the way to create Flash is different in IE/FF, so you may be getting the wrong one).
Check if you have correct SWF file - browser may cache older version... I.e. add element on the Flash control that simply shows static number and make sure it matches to latest one.

Categories