javascript - Adding div when clicking on anchor and removing div when clicking either outside of it or on a different anchor -
i have 2 anchor tags both display 2 different divs when clicked on want display 1 div @ time. want hide div displayed when clicking outside of it. done when click on first anchor , on second both divs displayed (i want 1 @ time).
here code:
//display , hide div number 1 $("a.number_1").on("click", function(event) { event.preventdefault(); $(".display_div_1").toggle(); event.stoppropagation(); }); $(".display_div_1").on("click", function(event) { event.preventdefault(); event.stoppropagation(); }); $(".body").on("click", function(event) { event.preventdefault(); $(".display_div_1").hide(); }); //display , hide div number 2 $("a.number_2").on("click", function(event) { event.preventdefault(); $(".display_div_2").toggle(); event.stoppropagation(); }); $(".display_div_2").on("click", function(event) { event.preventdefault(); event.stoppropagation(); }); $(".body").on("click", function(event) { event.preventdefault(); $(".display_div_2").hide(); });
div.body { background-color: white; width: 100%; height: 400px; border: 1px solid grey; } div.display_div_1 { display: none; } div.display_div_2 { display: none; } ul { margin: 0 0 30px 0; padding: 0px; } li { display: inline-block; } a.display { display: inline-block; background-color: lightblue; padding: 10px 20px; text-decoration: none; } div.display { background-color: grey; width: 100px; height: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="body"> <ul> <li> <a href="" method="post" class="display number_1">display div 1</a> </li> <li> <a href="" method="post" class="display number_2">display div 2</a> </li> </ul> <div id="first" class="display display_div_1"> div 1! </div> <div id="second" class="display display_div_2"> div 2! </div> </div>
my jquery code taken first answer post: https://stackoverflow.com/questions/30...
thank you!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <h1>blah</h1> <div class="body"> <ul> <li> <a href="#" method="post" id='div1' class="number">display div 1</a> </li> <li> <a href="#" method="post" id='div2' class="number">display div 2</a> </li> </ul> <div id="1" class="display display_div_1"> div 1! </div> <div id="2" class="display display_div_2"> div 2! </div> </div> </body>
with script
$( document ).ready(function() { $('.number').click(function() { $('div').hide(); //you can set class on divs , use if don't want hide divs $('.body').show(); $('.number').show(); $('#' + this.id.substring(3)).show(); //show div want show }); });
Comments
Post a Comment