开发者

Javascript function call on page both onload and onclick?

开发者 https://www.devze.com 2023-01-26 02:30 出处:网络
I need help with changing a function that is called once the page loads, and anytime afterwards when the user clicks on a certain div with an ID. So far I have this:

I need help with changing a function that is called once the page loads, and anytime afterwards when the user clicks on a certain div with an ID. So far I have this:

window.onload=function() {
//Do your stuff, JS!
}

Yes, I barely know any JS...

EDIT: I will include my JS function (I didn't make it myself, obviously another nice and smarter person did :P)

    function() {
    var maxHeight = 0;
    //get the column containers
    var colsA = document.getElementById("Content").childNodes;

    //get the height of the tallest column
    for(var i=0; i < colsA.length; i=i+1) {
         if(colsA[i].clientHeight > maxHeight) maxHeight = colsA[i].clientHeight;
    }

 //set all the column containers heights to maxHeight
    for(var i=0; i < colsA.length; i=i+1) {
         if(colsA[i].nodeType == 1) colsA[i].style.height = maxHeight+'px';
    }
} 

What it does: I have a div container tha开发者_高级运维t houses x number of column divs. These columns vary at height due to content. This function makes all the divs heights the same.

When my page loads, this code runs flawlessly. However afterwards, it doesn't. I have some collapsible divs that house extra information, when a user clicks it will push the height further. This is why I thought of an onclick for that id... unfortunately the id is dynamically generated by php.


You can define a function separately and then bind it to multiple event handlers:

function myHandler(){...}
window.onload = myHandler;
myElement.onclick= myHandler;
...


This should fix it:

function f() {
    // do your stuff
}

window.onload = f;
document.getElementById("myButton").onclick = f;


Another way:

window.onload=function() {
//Do your stuff, JS!
}

yourElement.onclick = window.onload;

In the end it does not matter how you do it. Functions are first class objects, so you just need to have a reference to the function.


To learn more about JavaScript, have a look at the MDC JavaScript Guide.

0

精彩评论

暂无评论...
验证码 换一张
取 消