views:

34

answers:

2

I have a simple function which I want to run on all elements with a certain class. I want this function to be run as soon as the DOM is loaded; not upon an event handler.

Below is the code that will run on an event handler like hover. How do I make it run as soon as the DOM is loaded?

$(document).ready(function(){
    var displayname = $(".displayname");

    function alignSpans(){
        var spanheight = this.offsetHeight;
        var cssbottom = spanheight + "px";
        this.style.bottom = cssbottom; 
    }

    displayname.hover(alignSpans);

});

displayname.alignSpans(); does not work

+2  A: 

Assuming displayname is a jQuery object, you can use .each() to call a callback function using this as the contained DOM elements (which is very conveniently the same convention as an event handler)

displayname.each(alignSpans);
gnarf
gnarf's answer is the simplest. If you wanted it to work with the format `displayname.alignSpans();` then you would need to create your `alignSpans` function as a jQuery plugin, i.e. adding it as a property to `$.fn`.
Jimmy Cuadra
+1  A: 

That's what the .each() function is for. I've made your code a bit more efficient too:

$(document).ready(function(){
    $(".displayname").each(function() {
        $(this).css("bottom", $(this).height()); 
    });
});
Ariel
jQuery will actually automatically add `px` if you just pass in `$(this).height()`
gnarf
That's good to know. I took out it (neat code is so much better...)
Ariel