milacay
milacay

Reputation: 171

Jquery - Loop Through An Array DIVs, show and hide them

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

Upvotes: 1

Views: 1161

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

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();
    }
});

Upvotes: 2

Related Questions