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.
Related
I need a little help for one function which is working only after a refresh. I`m not experienced with javascript and i need just to add one small "div" to already compliled project.
The index.html is
...
<body>
<script src="runtime-es2015-container.js" type="module">
<script src="runtime-es5-container.js" nomodule defer>
<script src="polyfils-es-5.js" defer>
<script>
window.addEventListener("DOMContentLoaded", function() {
setTimeout(() => {
let envContainer = document.querySelector('.info');
envContainer.setAttribute('style', 'flex-direction:column:');
let envRow = document.createElement('div');
envRow.classList.add('instance');
envContainer.appendChild(envRow).innerText = 'some text ';
},100);
}
....
The functional is working only after refreshing the page. I gues the problem is with selecting the '.info' , which is loaded before the function is executed.
Thanks,
Svetoslav
Just made a testrun of this and it seem to be working just fine, the only thing that was missing from your code was a ) in the end..
To me it looks like your problem is elsewhere. Well unless the info object is not created by code, then the problem is that it does not yet exist when you run this code..
--- Update ---
OKay so the div is created by js code and you have to wait for it.. the best idea I have is to poll and wait for it, I have updated the example to do just that and also changed to code to create the div after the first run of the function to simulate your situation.
function update_info() {
if(document.querySelector('.info')) {
let envContainer = document.querySelector('.info');
envContainer.setAttribute('style', 'flex-direction:column:');
let envRow = document.createElement('div');
envRow.classList.add('instance');
envContainer.appendChild(envRow).innerText = 'some text ';
} else {
setTimeout(() => {
update_info();
},100);
}
}
window.addEventListener("DOMContentLoaded", function() {
update_info();
const infodiv = document.createElement('div')
infodiv.id = "info";
infodiv.classList.add("info")
infodiv.innerHTML = "this first div";
document.body.appendChild(infodiv);
})
<body>
I see you have some errors in the code, try using this code which i fixed and changed a little bit and let me know if it works
<script>
window.addEventListener("load", function() {
setTimeout(() => {
let envContainer = document.querySelector('.info');
envContainer.setAttribute('style', 'flex-direction:column');
let envRow = document.createElement('div');
envRow.classList.add('instance');
envContainer.appendChild(envRow).innerText = 'some text ';
},100);
}
</script>
This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 1 year ago.
i want you to have to hold the button down for a second for it to start...
I've tried a couple of things like
function startHold1() {
setTimeout(function(){
startHold1A = setInterval(func1(), 250) }, 1000)
}
function endHold1() {
setTimeout(function(){
clearInterval(startHold1A, 950)
})
}
func1 basically adds 1 to a variable and displays it on the screen also i have a button that initiates startHold1 onmousedown and endHold1 onmouseup
I'm a super noob at code please help!
var setint = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
clearInterval(setint);
val = 0;
setint = setInterval(function () {
$("#putdata").val(++val);
console.log("mousehold");
},50);
});
$('#hold').on("mouseleave mouseup", function () {
val = 0;
$("#putdata").val(val);
clearInterval(setint);
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />
</body>
<html>
I have this function that alerts the user when their amount of "moonstone" is 10. However, for various reasons, I would like the if statement to be outside the function. When I do this though, the alert doesn't work. Could someone please explain and post a fix for it?
<!DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
}
if (newCounts == 10){
alert('10');
}
</script>
</html>
What does work, but that I don't want to use, is
<DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
if (newCounts == 10){
alert('10');
}
}
</script>
In your code you calling the totalcount() function on onclick event so whatever inside the totalcount() function will executed and code outside the totalcount() function will not execute
I'm not entirely clear why you wouldn't want the if test within the function. But, there is something that you could do:
const counter = {
value: 0,
addOne: function() {
this.value++;
if (this.value > 10) {
alert("Too many");
this.value--;
} else {
document.getElementById("counts").innerHTML = "Moonstones: " + this.value;
}
}
}
function updateCounter() {
counter.addOne();
}
<button onclick="updateCounter();">Add</button>
<div id="counts"></div>
This creates the counter as an object and includes an if test on a addOne function directly attached to that object. Whenever the updateCounter() function is called, the addOne function updates the counter value and checks to see if it has passed 10. If it has, the user gets and alert, otherwise the "counts" element gets updated.
But, as others have said, there is no real reason why an if test shouldn't be part of a function - perhaps you could explain your reasons for that requirement?
<!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.
I've got another JavaScript/jQuery-Problem. A minimal example could be this: I've got a div, and want some JavaScript executed, when the mouse enters. But for some reasons (= in reality, there a many divs, and for each data needs to be kept) I want to use a object as handler for the callback. Here's a small example:
function handler($thediv)
{
this.somedata = 8;
$thediv.mouseenter(function() { this.callback(); });
}
handler.prototype.callback = function()
{
alert(somedata);
}
An object is created when the document is loaded:
$(document).ready( function() {
new handler($("div"));
});
Nothing happens - except that the constructor is executed. I've tried and searched for hours now, but I can't fix this... probably too trivial?
Edit: A complete example.
<html>
<script type="text/javascript" src="jquery-1.6.js"></script>
</head>
<body>
<div>
blah blahasdasdadsssssssssssssss
asddddddddddddddddddddddddddd
</div>
</body>
<script type="text/javascript">
$(document).ready(function() {
new handler($("div"));
});
function handler($thediv)
{
this.somedata = 8;
$thediv.mouseenter(this.callback);
}
handler.prototype.callback = function()
{
alert(somedata);
}
</script>
</html>
The biggest issue here is the use of this in various contexts. Within the mouseenter function, this refers to div, not the object.
This should work:
http://jsfiddle.net/Nx5c7/
function handler($thediv)
{
this.somedata = 8;
this.theID=$thediv.attr("id");
var obj=this;
$thediv.mouseenter(function() {
obj.callback();
});
}
handler.prototype.callback = function()
{
alert(this.theID + " : " + this.somedata);
}