views:

37

answers:

1

I have a page with three HTML labels and their corresponding ASP.NET gridviews contained within divs. Now while learning jQuery, I am trying to achieve two things:
1. Change the css class of the lables upon mouse hover/out.
2. Slide up/down the grid div upon clicking of the labels.
It looks to be working as expected, but I wish to know if I am doing it the right way.

My complete jQuery code is:

$(function ColorChange(ID) {            
                $("#" + ID).toggleClass("gridLabel");
});
$(function ShowHide(GID) { 
                $('#' + GID).slideToggle('slow');
});

And I am calling these function from onmouseover, onmouseout and onclick events of the label controls passing in the label ID as parameter. As an example:

<label id="lblWebComp" class="gridLabelDefault" onmouseover="ColorChange('lblWebComp')"
                onmouseout="ColorChange('lblWebComp')" onclick="ShowHide('gvDivWC')">
                Web Components
</label>

Kindly let me know if this is the best way to achieve these effects? Don't I have to right the document ready function in the jQuery code?

Thanks a lot!

+2  A: 

The standard jQuery style is to bind all your functions from jQuery in document ready, as you kinda guessed already in your question.

So instead of

<label id="lblWebComp" class="gridLabelDefault" onmouseover="ColorChange('lblWebComp')"
                onmouseout="ColorChange('lblWebComp')" onclick="ShowHide('gvDivWC')">

in the html markup you might have simply

<label class="gridLabelDefault">

and then in jQuery:

$(document).ready(function() {
    $('.gridLabelDefault').click(function() { // this assigns the click to all elements with gridLabelDefault class
        // here you want to find which grid the clicked label corresponds to, as an example
        // I've used siblings, which you could use if your elements are within a shared parent div
        $(this).siblings('.grid').slideToggle('slow'); // assuming you grid has a 'grid' class
    });
});

That should hopefully give you an idea of the kind of code structure you should be aiming for, obviously you will need to tweak it to your requirements. The jQuery documentation is generally pretty good.

Regarding the css toggle, I don't really see from your example what benefits doing that in jQuery gives you. Just use the hover selector and do it in your css file. If you really want to use jQuery though, you can bind to the hover event in document ready in the same manner as I showed with the click event above.

$('.gridLabelDefault').hover(
    function () { // this is the mouseOver function
        $(this).addClass('gridLabel');
    }, 
    function () { // this is the mouseOut function
        $(this).removeClass('gridLabel');
    }
);
fearofawhackplanet
^^ thanks a ton for this explanation!
Dienekes