Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show hide DIVs : jQuery

Tags:

jquery

I have two links & I want to show / hide them one at a time, my code is :

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 <script type="text/javascript" src="js/jquery.js"></script>          
 <script type="text/javascript">                                         
   // we will add our javascript code here    
   $(document).ready(function() {
       $(function(){
           $('#link').click(function(){
           $('#colorDiv').slideToggle('slow');
            return false;
          });
        });
 });
 </script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
 #dv {
  width:100px;
  height:100px;
  border:1px solid;
}
</style>
</head>
<body>
<table cellspacing="2">
    <tr><td><a href="#" id="link">Color</a></td><td><a href="#" id="link">Car</a></td></tr>
    <tr><td><div id="colorDiv">Red</div></td><td><div id="carDiv">PRADO</div></td></tr>
</table>
</body>
</html>

by default first div should me shown. hanks.

like image 231
PHP Ferrari Avatar asked Nov 06 '22 13:11

PHP Ferrari


1 Answers

Here is your code with comments.

<!DOCTYPE html> 
<html> 
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<style>
#carDiv {
display: none; /* set initial carDiv visibility to hide */
} 
</style>
<style>
 #dv { 
  width:100px; 
  height:100px; 
  border:1px solid; 
} 
</style>
 <script type="text/javascript" src="js/jquery.min.js"></script>           
 <script type="text/javascript">
$(document).ready(function() {
  $('#link1').click(function(){ 
       $('#colorDiv').slideToggle('slow'); 
        return false; 
      }); 
 $('#link2').click(function(){ 
       $('#carDiv').slideToggle('slow'); 
        return false; 
      });     
  }) 
 </script> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
<!--[if IE]> 
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
<![endif]--> 
</head> 
<body> 
<table cellspacing="2"> 
<tr><td><a href="#" id="link1" class="link">Color</a></td><td><a href="#" id="link2" class="link">Car</a></td></tr> 
    <tr><td><div id="colorDiv">Red</div></td><td><div id="carDiv">PRADO</div></td></tr> 
</table> 
</body> 
</html> 

Remarks:

First - id should be a unique identifier, so I changed ids to link1 and link2.

Second No need to include 2 jquery libraries - use either one of them - local (src="js/jquery.min.js") or one from Google (src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js")

Third If You want to use multiple selectors, like You did that with multiple id "link", use class selector instead of id. Then in Jquery You select that using $('.link').click.... Google jquery selectors

like image 200
arunas_t Avatar answered Nov 15 '22 08:11

arunas_t