Charlie Kotter Charlie Kotter - 7 months ago 20
Javascript Question

To break up your jQuery code into functions, do you do it the same way as in JavaScript?

I've been writing some jQuery functions that have JavaScript variables and looping, etc inside them - they're becoming long and hard to read. If I want to break them up, how would I do that?

$(".x").click(function ()
{
var i=0;
for (i=0;i<50;i++)
{
if ($("#x"+i).is(':hidden'))
{
$("#x"+i).show();
}
else
{
$("#x"+i).hide();
}
}
});


For example, in the code above, if I want to move the contents of the loop to a separate function and then call that function from inside the loop, what would that need to look like?

Answer

There is no such thing as "jQuery functions", the jQuery code just usually uses an anonymous JavaScript function.

To move the contents of the loop into a named function would look like this:

$(".x").click( function() {
  for (var i=0; i<50; i++) toggleItem(i)
});

function toggleItem(i) {
  if ($("#x"+i).is(':hidden')) {
    $("#x"+i).show();
  } else {
    $("#x"+i).hide();
  }
}

However, you could use the cascading properties of CSS to toggle all the items with a simple JavaScript statement instead of looping through all the elements. Example:

CSS:

<style type="text/css">
.StateOne .InitiallyHidden { display: none; }
.StateTwo .InitiallyVisible { display: none; }
</style>

HTML:

<div class="StateOne" id="StateContainer">
   <div class="InitiallyVisible">Visible first</div>
   <div class="InitiallyHidden">Visible second</div>
   <div class="InitiallyVisible">Visible first</div>
   <div class="InitiallyHidden">Visible second</div>
   <div class="InitiallyVisible">Visible first</div>
   <div class="InitiallyHidden">Visible second</div>
   <div class="InitiallyVisible">Visible first</div>
   <div class="InitiallyHidden">Visible second</div>
</div>

JavaScript:

$('.x').click(function() {
   var s = document.getElementById('StateContainer');
   s.className = (s.className == 'StateOne' ? 'StateTwo' : 'StateOne');
});