Having multiple window.onload functions - javascript

I am having to use multiple window.onload functions on one page because the JS plugin that I am using is calling the window.onload function already. I would like to not edit the plugin and work around it. Here is what I have tried:
<div id="Count"></div>
//<script type="text/javascript" src="plugin.js" /> // JS plugin using window.onload
var INCREMENT = 3;
var count = 0;
var msInterval = 800;
var oldonload = window.onload; // assigning current window.onload to a variable
window.onload = function() { <-- error line
if (oldonload) {
oldonload();
}
document.getElementById('Count').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('Count').innerHTML = count;", msInterval);
}
I am getting this error:
TypeError: (intermediate value)(...) is not a function

Try using addEventListener instead.
function myFunction() {
// do stuff here
}
window.addEventListener("load", myFunction, false);

Related

Javascript function being executed even if its not called

Hi so I'm fairly new to javascript and right now, I'm experimenting in defining functions and hiding/showing specific elements.
in this simple program that I made, I am trying to show a loading screen while a function is still executing. the problem is, the function that is inside the onlick event handler executes even without clicking the button
<body>
<button id="thisbutton" type="button">clickme</button>
<div>
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>
</div>
<div id="loadss" class="LockOn"></div>
<script>
document.getElementById("thisbutton").onclick(meow());
document.onload = rawr();
function rawr() {
document.getElementById("loadss").style.visibility = "hidden";
document.getElementById("loadss").style.display = "none";
}
function meow() {
document.getElementById("loadss").style.visibility = "visible";
document.getElementById("loadss").style.display = "block";
time();
document.getElementById("loadss").style.visibility = "hidden";
document.getElementById("loadss").style.display = "none";
};
function time() {
var timeleft = 10;
var downloadTimer = setInterval(function () {
timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
if (timeleft <= 0)
clearInterval(downloadTimer);
}, 1000);
}
</script>
In Javascript, functions are first-class citizens. This means you can treat them like most variables:
function test () { console.log('Hi!'); }
var x = test;
And you can execute them by using parentheses on any reference to them:
test(); // will execute function test
x(); // will _also_ execute function test
Hence, your code:
document.getElementById("thisbutton").onclick(meow());
document.onload = rawr();
is executing the functions meow and rawr. You perhaps want to pass references to these functions:
document.getElementById("thisbutton").onclick(meow);
document.onload = rawr;
your code
document.getElementById("thisbutton").onclick(meow());
should be like following
document.getElementById("thisbutton").onclick = meow;
notice i did not call the meow function and onclick is not a function but a property.
also your code
document.onload = rawr;
should be
document.onload = rawr;
when you use parentheses then the function gets called.

Is something like window.onload OR window.onresize then do this function possible?

I have a function that should be called either on load or on resize.
Is it possible to combine it somehow?
var loadOrNotImages = function() {
if(window.innerWidth > 640) {
var imgs = document.querySelectorAll('.img--only-on-high-reso');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = imgs[i].attributes["data-src"].value;
imgs[i].alt = imgs[i].attributes["data-alt"].value;
}
}
}
window.onload = function(){
loadOrNotImages();
}
window.onresize = function() {
loadOrNotImages();
}
There's nothing wrong with how you're doing it now except you don't need the wrappers, just:
window.onload = loadOrNotImages;
window.onresize = loadOrNotImages;
...or even
window.onload = window.onresize = loadOrNotImages;
...or better yet, in the modern world, use addEventListener.
The DOM itself doesn't have a function for hooking up a function to multiple events at once. You could readily give yourself one:
function on(target, eventNames, handler) {
eventNames.split(" ").forEach(function(eventName) {
target.addEventListener(eventName, handler);
});
}
then
on(window, "load resize", loadOrNotImages);

Why my function is running before window resizes?

I want the header to change it's colour when the window is re-sized. But the changeColor() runs immediately after I load the site. Can anyone explain, why my changeColor() function is running before window re-sizes?
<body>
<h1>JavaScript</h1>
<script>
var heading = document.querySelector("h1");
function changeColor(colour) {
heading.style.color = colour;
}
window.onresize = changeColor("red");
</script>
</body>
You are executing "changeColor" function in your way.
Try this:
<body>
<h1>JavaScript</h1>
<script>
var heading = document.querySelector("h1");
function changeColor(colour) {
heading.style.color = colour;
}
window.onresize = function() {
changeColor("red")
};
</script>
</body>
You are invoking the function.
use this:
window.onresize = changeColor.bind(this,"red");
Right now, the execution of your program is:
changeColor(red) --> assign its return value to window.onresize
You're assigning the result of a call to changeColor to window.onresize, not the function changeColor itself. Your code is equivalent to:
var temp = changeColor("red"); // undefined, because changeColor doesn't return anything
window.onresize = temp;
What you can do is create a function that returns a function which uses the desired color:
function createColorChangeCallback(color) {
return function() {
heading.style.color = color; // color variable captured from enclosing function
};
}
window.onresize = createColorChangeFunction("red");
Or you can use .bind or a lambda:
window.onresize = function() {
changeColor("red");
};
Which are both equivalent to:
window.onresize = function() {
heading.style.color = "red";
};
you should try something like this and that should do the trick
<body onresize="changeColor('red');">
$(document).ready(function(){
$(window).resize(function(){
heading.style.color = "red";
});
});
Try this....

Chrome Extension - How to pass variables from JS to popup.html?

I have some variables in the following JS:
document.addEventListener('DOMContentLoaded', function (){
document.getElementById('btn4').addEventListener('click', getbg);
});
getbg = function()
{
chrome.runtime.getBackgroundPage(
function (bg) {
var allcompanynames = bg.companynames;
alert(allcompanynames)})
}
As you can see, the variable is "allcompanynames".
However, how do I pass them and show it on the popup.html page?
I have tried
<script type="text/javascript" src="companynames.js"></script>
<p id="allcompanynames"></p>
no luck. What's wrong?
document.addEventListener('DOMContentLoaded', function (){
document.getElementById('btn4').addEventListener('click', getbg);
});
getbg = function()
{
chrome.runtime.getBackgroundPage(
function (bg) {
var allcompanynames = bg.companynames;
alert(allcompanynames)})
document.getElementById("allcompanynames").innerHTML(allcompanynames)
}
I'm guessing you should add that last line after displaying the pop up to add the content into the page.
Write your code in this way
var background = chrome.extension.getBackgroundPage();
var allcompanynames = background.companynames;
alert(allcompanynames)

Assign onchange to an object and pass a parameter

So I have the following JavaScript:
<script language=JavaScript>
function reload(form){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;
</script>
But then it keeps on reloading itself constantly. Which is expected. But how can I assign reload and pass a function instance to it?
I could do:
<script language=JavaScript>
function reload(){
var form = document.getElementById("myform");
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
function init(){
document.getElementById("id_profile").onchange = reload;
}
window.onload = init;
</script>
But what if I have more forms? Or I let say I want to reuse reload on multiple pages with different form names.
I would like to avoid setting onchange in the HTML tag though:
onchange="reload(this.form)"
If this is possible at all?
Thanks!
But what if I have more forms?
You can assign the same function to all the profile elements in the forms, and reference the element that received the change event inside the function using this.
<script type="text/javascript">
function reload(){
// In here, "this" is the element that received the event
var val = this.options[ this.options.selectedIndex ].value;
self.location='?profile=' + val ;
}
function init(){
var len = document.forms.length;
while( len-- ) {
document.forms[ len ].profile.onchange = reload;
}
}
window.onload = init;
</script>
You can make a function that returns a function (a closure) for the reload function.
function reload(form){
return function(){
var val=form.profile.options[form.profile.options.selectedIndex].value;
self.location='?profile=' + val ;
}
}
function init(){
var form = document.getElementById("myform");
document.getElementById("id_profile").onchange = reload(form);
}
window.onload = init;

Categories

Resources