1

I am new to JQuery/Javascript. Is there a good way to put bunch of elements in an array and loop through it, call a function to do something. Lets me explain what I am trying to do.

I have this code below will hide and show the 2 DIVs when the mouse click outside of the DIV. It works great. However, I have alot of DIVs to show and hide. Please show me a way to put in a array of DIVs, convert below code to the function ShowHideDIV(hideDiv, showDiv) to perform the action?

$(document).mouseup(function (e)
{
    var showContainer1 = $("#divShipMethod");
    var hideContainer1 = $("#divShipMethodDDL");

    if (!hideContainer1.is(e.target) 
        && hideContainer1.has(e.target).length === 0) 
    {
        hideContainer1.hide();
        showContainer1.show();
    }
});

For example, Says I have the following DIV IDs like to put in an array:

  1. divShow1
  2. divHide1
  3. divShow2
  4. divHide2
  5. divShow3
  6. divHide3
  7. divShow4
  8. divHide4
  9. divShow5
  10. divHide5
4
  • You can use $.each() to loop through an array with jQuery. Commented Oct 22, 2013 at 21:40
  • 2
    You likely don't need to loop at all, a common classname among the differing types of divs would probably be easier to maintain. Commented Oct 22, 2013 at 21:41
  • how can I put those DIVs in an array and loop through it? I am new to Jquery, code example would be appreciated. thanks Commented Oct 22, 2013 at 21:42
  • 1
    Just like Kevin indicated, the "jQuery way" is to use classes and ids appropriately and refer to the items in that way. So if you want to deal with all of those divs together, they should be in a class (by adding class="foo" to the divs) and then you refer to them all with $('.foo'). Then you could loop them like $('.foo').each(function () { /* do something */ }; or perhaps hide them all with $('.foo').hide(); with no loop at all. Commented Oct 22, 2013 at 21:48

1 Answer 1

2

Instead of using IDs for your divs, give them a class name (all the same)

$(document).mouseup(function (e)
{
    var showContainer1 = $(".divShipMethod");   
    var hideContainer1 = $(".divShipMethodDDL");

    if (!hideContainer1.is(e.target) 
        && hideContainer1.has(e.target).length === 0) 
    {
        hideContainer1.hide();
        showContainer1.show();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.