Assign onchange to an object and pass a parameter - javascript

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;

Related

How do I add this code to what I already have in oder for this code to work

I would like to implement the second code into the first one in order for it to work as intended. I am unsure how to do this
Current code:
<script type="text/javascript">
!function(){
var campaign_link = ""; // REPLACE WITH YOUR LINK
var t;
try{
for(t=0;10>t;++t)history.pushState({},"","#");
onpopstate=function(t){t.state&&location.replace(campaign_link + window.location.search.substring(1))}}
catch(o){}
}();
</script>
the code I would like to add to existing code;
window.addEventListener("popstate", function(e) {
window.location.href = location.href;
});
You can just add this function to your current script like so. However you may want to store the loction.href in a var as opposed to window.location
<script type="text/javascript">
function(){
var campaign_link = ""; // REPLACE WITH YOUR LINK
var t;
try{
for(t=0;10>t;++t)history.pushState({},"","#");
onpopstate=function(t){t.state&&location.replace(campaign_link + window.location.search.substring(1))}}
catch(o){}
}();
window.addEventListener("popstate", function(e) {
window.location.href = location.href;
});
</script>

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)

Having multiple window.onload functions

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);

How can i optimize my Jquery code?

I've created some JavaScript using Jquery, for the page animation :
I trying to optimize it since i repeat the same thing for subtab1, subtab2, subtab3.
The same function is executed for all of them, and the only thing is changes is variable i iterating on?
Any suggestion?
<script type="text/javascript">
$(document).ready(function () {
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
var $fundosdiponiveis = $('#fundosdiponiveis');
var $fundosdiponiveisTab = $('#tabs1');
$defensivo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$defensivoSubTab.removeClass("hide");
$defensivoSubTab.show();
});
$equilibrado.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$equilibradoSubTab.removeClass("hide");
$equilibradoSubTab.show();
});
$activo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$activoSubTab.removeClass("hide");
$activoSubTab.show();
});
});
</script>
For a while:
var $fundosdiponiveis = $('#fundosdiponiveis');
This is my default div.
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
That divs apears when i clicking on one of the following tabs:
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
And that button hides and changes style"display" to none, on click, of my three #subtab's
var $fundosdiponiveisTab = $('#tabs1');
Any suggestion?
You could write a function that returns the proper function:
function createShowTabFunc(tab) {
return function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
tab.removeClass("hide");
tab.show();
}
}
Then assign your click handlers:
$defensivo.live('click', createShowTabFunc($defensivoSubTab));
$equilibrado.live('click', createShowTabFunc($equilibradoSubTab));
$activo.live('click', createShowTabFunc($activoSubTab));
Have a common class attribute to all the tab's and you just need to write $('.class').click() and in this get the id of the corresponding tab and according to the id fetched by attr function, you can have an if else to define your variables inside the if else and execute your code block.

Help converting JavaScript click function to onLoad

I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.

Categories

Resources