Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to optimize this javascript code?

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();
});
like image 548
nueq Avatar asked Nov 29 '22 09:11

nueq


2 Answers

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>
like image 192
Carsten Løvbo Andersen Avatar answered Dec 01 '22 23:12

Carsten Løvbo Andersen


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>
like image 44
Anil Panwar Avatar answered Dec 01 '22 22:12

Anil Panwar