Skip to content Skip to sidebar Skip to footer

Find Currently Visible Div In Jquery

I have a four divs all set display:none and on document.ready i am showing the first div.. I have 4 link buttons link1,link2...link4... I showing div1 on link1 click and so on.. Ho

Solution 1:

with lesserr codes, you could do it this way...

jQuery

<scripttype="text/javascript">
    $(document).ready(function() {
          $("#div1").show().fadeIn("slow");
    });
    $('.links a').click(function() {
        $(".ContentDivs:visible").fadeOut("fast");//find current div here?
        $("#div" + ($(this).index()+1)).show().fadeIn("slow");
    });
</script>

html

<div><divclass="links"><aid="Link1"href="#">Link1</a><aid="Link2"href="#">Link2</a><aid="Link3"href="#">Link3</a><aid="Link4"href="#">Link4</a></div><divid="div1"class="ContentDivs">
        DIv1
    </div><divid="div2"class="ContentDivs">
        Div2
    </div><divid="div3"class="ContentDivs">
        Div3
    </div><divid="div4"class="ContentDivs">
        Div4
    </div></div>

demo

Solution 2:

You can use the :visible filter selector for that.

$('.ContentDivs:visible').........

Update:

An easier approach will be to give each of your links a rel attribute with the same value as the id of divs and a class, eg:

<aclass="link"href="#"></a><aclass="link"href="#"></a>

And divs:

<div id="">
  Div1
</div>

<div id="">
  Div2
</div>

And then all you need is to get the rel of clicked link and show/hide the corresponding div:

$('a.link').click(function(){
  var rel = $(this).attr('rel');

  if ($('div#' + rel).is(':visible'))
  {
    $('div#' + rel).fadeOut('fast');
  }
  else
  {
    $('div#' + rel).fadeIn('fast');
  }

  returnfalse;
});

Solution 3:

Use

$(".ContentDivs:visible");

Solution 4:

try

var displayedDiv = $('div.ContentDivs').filter(':visible');

or even this

var displayedDiv = $('div.ContentDivs').filter(function(){
       if($(this).css('display') != 'none')
          returntrue;
       elsereturnfalse;
       });

Solution 5:

This should work:

HTML

<div><divid="links"><aid="Link1"href="#"rel="div1">Link1</a><aid="Link2"href="#"rel="div2">Link2</a><aid="Link3"href="#"rel="div3">Link3</a><aid="Link4"href="#"rel="div4">Link4</a></div><divid="div1"class="ContentDivs">
    DIv1
    </div><divid="div2"class="ContentDivs">
    Div2
    </div><divid="div3"class="ContentDivs">
    Div3
    </div><divid="div4"class="ContentDivs">
    Div4
    </div></div>

Javascript

$(function () {
    $("#links a").click( function () {
        $(".ContentDivs").css( "display", "none");
        $("#"+this.rel+".ContentDivs").fadeIn();
    });

});

Post a Comment for "Find Currently Visible Div In Jquery"