Javascript function does not get passed paramrter - javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
(function setFont() {
var i;
for ( i = 0; i < document.all.length; i++) {
document.all[i].style.fontFamily = "Verdana";
document.all[i].style.fontSize = "16";
document.all[i].style.color="black";
}
})();
(function abc(a)
{
alert(a);
ansArray = ['a'];
for(i=1;i<=a;i++)
{
document.write('<input type = "button" value = "a">');
document.write('<input type = "button" value = "b">');
}
var myButton = document.getElementsByTagName("input");
//alert(myButton.length);
myButton[0].onclick = function() {
if(ansArray[0] == 'a')
myButton[0].style.backgroundColor = "green";
else
myButton[0].style.backgroundColor = "red";
};
myButton[1].onclick = function() {
if(ansArray[0] == 'b')
myButton[1].style.backgroundColor = "green";
else
myButton[1].style.backgroundColor = "red";
};
})();
setFont();
</script>
</head>
<body onload="abc(2)">
</body>
</html>
A javascript function abc(a) does not get the value 2 passed from <body onload = "abc(5)">. It says undefined. How to pass the parameters in a javascript function. I have posted it earlier as well but the parameter was not there, on giveing the parameter i found the problem.Please help me. Thanks in advance

Your function is a closure, it's not exposed to the public but it is executed right after it's created.
And then it's gone.
It's not there to look cool, it has its purpose. Just make normal functions to get it work
(function(a) {
// immediately called and 'garbaged'
})(a);
vs.
function publicAlwaysCallable(a) {
console.log(a); // call me when you like
}

You don't have to use immediate function in this case. Declare it like this:
function abc(a) { ... }
If for some reason you want to encapsulate your code into closure you can do it like this:
(function(export) {
export.abc = function(a) { ... };
...
})(window);

The normal function (not closure) function abc(a){ ... } with the button click handlers are to be called at the end of the script. Not on onload event of the page. Now it works in IE9 also
Thanks everybody for your valuable suggestions.

Related

Sending a variable from popup.js to content script

Is it possible for me to pass a variable from my popup.js and use it globally in my content script? I need to be able to pass a variable from the popup and use it in my content script as a variable. I've tried all sorts of answers but I'm still stuck.
Below is a code snippet where I would have to use the user input assigned to minNum:
if (checkPage() == true) {
if (num <= minNum) {
console.log('Leaving call.');
leaveCall();
}
}
Below are my popup.js and popup.html file that just adds or reduces variable people:
people = 3;
document.addEventListener(
'DOMContentLoaded',
function () {
var addButton = document.getElementById('add');
var reduceButton = document.getElementById('reduce');
addButton.addEventListener(
'click',
function () {
people += 1;
document.getElementById('minNum').innerHTML = people;
},
false
);
reduceButton.addEventListener(
'click',
function () {
people -= 1;
document.getElementById('minNum').innerHTML = people;
},
false
);
},
false
);
<!DOCTYPE html>
<html>
<head>
<title>Yeet Meet</title>
</head>
<body>
<h1 id="minNum">3</h1>
<button id="add">+</button>
<button id="reduce">-</button>
<script src="popup.js"></script>
</body>
</html>
I want to pass variable people to my content script so that I could assign it to minNum.
I apologize if this has already been answered and it probably just flew over my head but I can't seem to make anything work. Thank you for your help.

Refer JS object in HTML element generated by this object

My JavaScript object create some HTML elements (two buttons for example) and after user click on these buttons I should call some method of this object. So the question is how I can refer JS object in HTML element to call its method?
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myObj(){
this.a = null;
this.setA = function(a){
this.a = a;
}
this.requestA = function(){
$( "body" ).append($('<input><button onclick="referenceToMyObject.setA($(this).prev().val());">Set A</button>'));
}
return this;
}
</script>
</head>
<body>
<script>
var myObjInst = myObj();
myObjInst.requestA();
</script>
</body>
Creating the event handler inline (onclick="foo()") won’t allow you to reference the object, and is discouraged in any case because you should avoid evaluating strings as code. In addition, your code bypasses JavaScript’s idea of objects somewhat. You can reformulate it as follows:
function MyObj() {
this.a = null;
}
MyObj.prototype.setA = function(a) {
const old = this.a;
this.a = a;
console.log("Updated a from", old, "to", this.a);
};
MyObj.prototype.requestA = function() {
const input = $("<input type='text'>");
const button = $("<button>Set A</button>");
button.click((e) => {
this.setA($(e.target).prev().val());
});
const body = $("body");
body.append(input);
body.append(button);
};
$(document).ready(() => {
const myObjInst = new MyObj();
myObjInst.requestA();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here, we use button.click to define the event handler and new MyObj() to instantiate the object. Apart from that, I cleaned up the code a bit and added a bit of logging so you can see what’s going on.
You could still define setA and requestA within the constructor, as you do in your example. I chose to define them on the prototype since their behaviour is the same across instances.
Try this and please let me know if this works for you.
(working example in JSFiddle https://jsfiddle.net/galeroy/9nocztk4/1/)
<!doctype html>
<html>
<head>
<script>
var myObject = {
createButton: function(){
var p = document.getElementById('par')
var b = document.createElement('button');
b.innerHTML = 'click me';
b.setAttribute('onclick', 'myObject.myMethod()'); // this is the important part
p.appendChild(b);
},
myMethod: function(){
alert("Button created by object, when clicked, calls another method in the same object")
}
}
function init(){
myObject.createButton();
}
</script>
</head>
<body onload="init()">
<p id="par"></p>
</body>
</html>

Click handler losing reference to "this" object that created it

I made JS script:
var zzz;
zzz = {
fff: function (Id) {
alert("You did it! Id="+Id);
},
main: function (Id) {
var button, elements;
button = document.createElement("input");
button.type = "submit";
button.onclick = function () {
zzz.fff(Id);
};
elements = document.getElementById(Id);
elements.appendChild(button);
}
};
and HTML, where I tested it:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<title>My Web Page!</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="div001"></div>
<div id="div002"></div>
<script type="text/javascript">
object1 = zzz;
object1.main("div001");
object2 = zzz;
object2.main("div002");
</script>
</body>
</html>
Why it works only if I write button.onclick = function () { zzz.fff(Id); }; and with this.fff(Id) it doesn't work?
When you bind an event handler (such as onclick), inside the handler this becomes the element that triggered the event (except if you used an inline onclick="" attribute, which should be avoided).
Instead of using zzz, you could also copy this to another variable that would be available inside the handler via closure:
var that = this;
button.onclick = function () {
that.fff(Id);
};
Or you could use Function.prototype.bind:
var clickHandler = button.onclick = function () {
this.fff(Id);
};
button.onclick = clickHandler.bind(this);

javascript - passing additional parameters into an event handler

I have a javascript object which has some defined variables and attaches some event handlers. I'd like the event handlers to have access to the defined variables. Is there a way to do that ? The event-handlers are within their own local scope so don't have access to the object variables. Is there a way to pass them in without using global variables ?
I have an idea that closures would solves this but I'm not sure how.
the code below will print the object name when the page loads but when you click on the map dom object it will say name is undefined.
All help much appreciated.
Colm
<!DOCTYPE html>
<html lang="en">
<head>
<title>Map Test</title>
<meta charset="utf-8" />
<script type="text/javascript">
window.onload = function() {
var e = new EvtTest();
e.printName();
e.attachEvents();
};
function EvtTest() {
this.name = "EvtTest";
}
EvtTest.prototype.name = null;
EvtTest.prototype.attachEvents = function () {
var map = document.getElementById("map");
map.addEventListener ('click', this.evtHandler, false);
};
EvtTest.prototype.printName = function () {
console.log ("This Name : " + this.name);
};
EvtTest.prototype.evtHandler = function (e) {
e.preventDefault();
console.log ("Name : " + this.name);
};
</script>
<style type="text/css">
html, body {
height:100%;
width:100%;
margin: 0;
background-color:red;
}
#map {
height: 300px;
width: 300px;
background-color:yellow;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
A little bit of fiddling:
EvtTest.prototype.attachEvents = function () {
var that = this;
var map = document.getElementById("map");
map.addEventListener ('click', function () {
that.evtHandler();
}, false);
};
Now this inside evtHandler references the object you expected.

Why doesn't function.apply() work across document boundaries in IE?

I'm seeing some strange behavior in IE trying to call functions in another page via function.apply().
Here's a simple test case:
test1.html:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
var opened = null;
function applyNone() {
opened.testFunc.apply(opened);
}
function applyArgs() {
opened.testFunc.apply(opened, ["applied array"]);
}
function call() {
opened.testFunc("called directly");
}
function remoteApply() {
opened.testApply(["used remote apply"]);
}
function remoteApplyCopy() {
opened.testApplyCopy(["used remote apply copy"]);
}
function openPopup() {
opened = window.open("test2.html", "_blank");
}
</script>
</HEAD>
<BODY>
OPEN
<hr>
applyNone
applyArgs
call
remoteApply
remoteApplyCopy
</BODY>
</HTML>
test2.html:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
function testApply(args) {
testFunc.apply(this, args);
}
function testApplyCopy(args) {
var a = [];
for(var i = 0; i < args.length; i++) {
a.push(args[i]);
}
testFunc.apply(this, a);
}
function testFunc() {
var s = "Got: ";
for(var i = 0; i < arguments.length; i++) {
s += arguments[i] + " ";
}
document.getElementById("output").innerHTML += s + "<BR>";
}
</script>
</HEAD>
<BODY>
Hi there
<div id="output"/>
</BODY>
</HTML>
In firefox and chrome all methods work properly.
In IE (tested in 6, 7, and 8) all but the applyArgs() and remoteApply() methods work as expected.
applyArgs() gives a "JScript object expected" error when it tries calling apply (test1.html line 11).
remoteApply() gives the same "JScript object expected" error when it tries calling apply (test2.html line 5).
Problem is, I need to be able to use apply(). I can get around the issue by doing something like the remoteApplyCopy() mechanism, but I'm trying to avoid that. Why doesn't apply() just work?
You need to have the arrays created in the other window, because each window has its own Array constructor. I think this will work.
Add this function to test2.html:
function getEmptyArray() {
return new Array();
}
And this function to test1.html:
Array.prototype.cloneToRemote = function (win) {
var newArray = win.getEmptyArray();
for (var i = 0; i < this.length; i++)
{
newArray.push(this[i]);
}
return newArray;
}
Then do this:
function applyArgs() {
opened.testFunc.apply(opened, ["applied array"].cloneToRemote(opened));
}
Note, it seems like you should be able to do
var newArray = new win.Array();
within the test1.html cloneToRemote() function, but I couldn't make that work. If you could do that, you could get rid of the new getEmptyArray() function in test2.html.
I have no idea why this works, but I was playing around with your code and stumbled across one solution... put test2's functions inside of test1 and it works:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
var opened = null;
function applyArgs() {
testFunc.apply(opened, ["applied array"]);
}
function openPopup() {
opened = window.open("test2.html", "_blank");
}
function testFunc() {
var s = "Got: ";
for(var i = 0; i < arguments.length; i++) {
s += arguments[i] + " ";
}
this.document.getElementById("output").innerHTML += s + "<BR>";
}
</script>
</HEAD>
<BODY>
OPEN
<hr>
applyArgs
</BODY>
</HTML>
I'll let you know if I can figure out any more (IE is weird like that). Like I said, I was just toying with the code.
If you change test2.html testApply() function as follows:
function testApply() {
testFunc.apply(this, arguments);
}
remoteApply() works. But, applyArgs() still failed.
"...
applyArgs() gives a "JScript object expected" error when it tries calling apply (test1.html line 11).
remoteApply() gives the same "JScript object expected" error when it tries calling apply (test2.html line 5).
..."
Which exact object is not "JScript object" as "expected" ?
(hint: use debugger)
--DBJ

Categories