Matias Valdiviezo Matias Valdiviezo - 2 months ago 8
Javascript Question

jquery click on menu and show/hide divs [solved]

I need help for solving this jQuery problem. I have a menu made with bootstrap, I need to show a div when click in a menu item, and hide others. the divs are A B C, for menus A B C. They have to show in the empty white space.

enter image description here

<ul class="nav nav-pills nav-stacked">
<li class="active"><a href="#"><i class="glyphicon glyphicon-dashboard"> </i>A</a></li>
<li><a href="#"><i class="glyphicon glyphicon-cd"> </i>B</a></li>
<li><a href="#"><i class="glyphicon glyphicon-facetime-video"> </i>C</a></li>
</ul>


I have solved this ussing my own code, thanks anyway.

$(document).ready(function(){
$('#contenido-dashboard').show();
$('#musica-dashboard').hide();
$('#video-dashboard').hide();
$('#dashmenu').click(function(){
$('#video-dashboard').hide();
$('#musica-dashboard').hide();
$('#contenido-dashboard').show();
});
$('#dashmusica').click(function(){
$('#contenido-dashboard').hide();
$('#video-dashboard').hide();
$('#musica-dashboard').show();
});
$('#dashvideo').click(function(){
$('#contenido-dashboard').hide();
$('#musica-dashboard').hide();
$('#video-dashboard').show();
});
});

Answer

Try this.

jQuery(function($){
    $("ul li").click(function(){
        var id = $(this).attr("id");
    
        $(".wrapper > div").removeClass("visible");
        $(".wrapper > div." + id).addClass("visible");
    });
});
ul{
  padding: 0;
  margin-bottom: 10px;
}
ul li{
  cursor: pointer;
  list-style: none;
}

ul li:hover{
  color: blue;
}

.wrapper > div{
  width: 100px;
  height: 100px;
  display: none;
}
.wrapper > div.visible{
  display: block;
}
.wrapper > div.purple{
  background-color: purple;
}
.wrapper > div.green{
  background-color: green;
}
.wrapper > div.blue{
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul>
  <li id="purple">A</li>
  <li id="green">B</li>
  <li id="blue">C</li>
</ul>

<div class="wrapper">
  <div class="purple visible"></div>
  <div class="green"></div>
  <div class="blue"></div>
</div>

Comments