stockoverflow
stockoverflow

Reputation: 1457

Javascript function call on page both onload and onclick?

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 that 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.

Upvotes: 1

Views: 10349

Answers (3)

Felix Kling
Felix Kling

Reputation: 816302

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.

Upvotes: 0

Dan Inactive
Dan Inactive

Reputation: 10060

This should fix it:

function f() {
    // do your stuff
}

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

Upvotes: 1

Simon
Simon

Reputation: 3539

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

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

Upvotes: 8

Related Questions