daru79
daru79

Reputation: 31

Show particular div and hide all another after click event

I have three div elements:

<div class="hide_banner" id="1"><img src="1.png"></div>
<div class="hide_banner" id="2"><img src="2.png"></div>
<div class="hide_banner" id="3"><img src="3.png"></div>

After the page is loaded the user should see the 1st div only. Here is the JS/jQ code (this works perfectly):

$(document).ready(function() {
  $('.hide_banner').not('#' + 1).hide(3000);
});

The user can pick another banner by click at links on this page:

<ul class="dropdown-menu" role="menu">
  <li><a href="#1" class="show_banner">Image 1</a></li>
  <li><a href="#2" class="show_banner">Image 2</a></li>
  <li><a href="#3" class="show_banner">Image 3</a></li>
</ul>

After click for example on the 3rd link (href="#3") the div with id="1" should hide and the div with id="3" shold be shown. I have an idea how to maintain the problem combaining with PHP, but i want to solve it with JS/jQ only, so please help! ;) Here is my JS/jQ code which doesn't work:

$(document).ready(function() {
  $('.hide_banner').not('#' + 1).hide(3000);
  $('a').click(function() {
    var id = $(this).attr('href');

    if(id == 1) {
        $(id).show(3000);
        $('#2').hide(3000);
        $('#3').hide(3000);

    }

    if(id == 2) {
        $(id).show(3000);
        $('#1').hide(3000);
        $('#3').hide(3000);

    }

    if(id == 3) {
        $(id).show(3000);
        $('#1').hide(3000);
        $('#2').hide(3000);

    }
  });

});

P.s.: I know that it is incorrect to start id's names with a number ;)

Upvotes: 0

Views: 825

Answers (2)

Jamiec
Jamiec

Reputation: 136249

Really, no need for if...else logic here, nor any need to specify the first id - just use :first:

$('.hide_banner').not(':first').hide(3000);
$('a').click(function() {
    var id = $(this).attr('href');
    $(id).show(3000);
    $('.hide_banner').not(id).hide(3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="hide_banner" id="1">1</div>
<div class="hide_banner" id="2">2</div>
<div class="hide_banner" id="3">3</div>


<ul class="dropdown-menu" role="menu">
  <li><a href="#1" class="show_banner">Image 1</a></li>
  <li><a href="#2" class="show_banner">Image 2</a></li>
  <li><a href="#3" class="show_banner">Image 3</a></li>
</ul>

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

You already know how to use jQuery not, so use it to exclude the selected target:

JSFiddle: http://jsfiddle.net/vk94mmv2/2/

$(document).ready(function () {
    $('.hide_banner:not(:first)').hide(3000);
    $('a').click(function () {
        var id = $(this).attr('href');
        var $show = $(id);
        $show.show(3000);
        $('.hide_banner').not($show).hide(3000);
    });
});

Note: you can change the first selector to use the :not(:first) pseudo selectors to select all but the first banner.

Upvotes: 0

Related Questions