How to optimize this functions? Can I make one function for all operations?
$('#b-hat1').click(function() {
$('#hat3').hide();
$('#hat2').hide();
$('#hat1').show();
});
$('#b-hat2').click(function() {
$('#hat3').hide();
$('#hat2').show();
$('#hat1').hide();
});
$('#b-hat3').click(function() {
$('#hat3').show();
$('#hat2').hide();
$('#hat1').hide();
});
Without your html, i can only give you a "rought" idea about how to solve it.
$("div[id^='hat']").hide();
hides all the div's that starts with hat
$('div[id^="b-hat"]').click(function() {
var id = $(this).attr("id").replace("b-","");
$("div[id^='hat']").hide();
$('#' + id).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hat1">hat1</div>
<div id="hat2">hat2</div>
<div id="hat3">hat3</div>
<br><br>
<div id="b-hat1">Show hat1</div>
<div id="b-hat2">Show hat2</div>
<div id="b-hat3">Show hat3</div>
Will show the div only after click on particular button DEMO:
$(document).ready(function(){
$(".hat").hide();
$(".clickMe").on("click",function(){
var showDiv = $(this).data("id");
$(".hat").hide();
$("#hat_"+showDiv).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button class="clickMe" data-id="1" type="button">1</button>
<button class="clickMe" data-id="2" type="button">2</button>
<button class="clickMe" data-id="3" type="button">3</button>
<div id="hat_1" class="hat">hat_1</div>
<div id="hat_2" class="hat">hat_2</div>
<div id="hat_3" class="hat">hat_3</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With