4

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();
});

3
  • 5
    Could you please add your HTML code to the question so we can see how the #b-hatX relate to the #hatX elements Commented Feb 23, 2017 at 9:00
  • add your HTML code Commented Feb 23, 2017 at 9:01
  • 2
    Probably by not using IDs in the first place (that's why you've been asked for HTML, since it's the most relevant bit). Commented Feb 23, 2017 at 9:10

2 Answers 2

14

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>

Sign up to request clarification or add additional context in comments.

8 Comments

what doing this operator '^=' ?
The ^= in id^='hat means it takes all id's that starts with "hat"
Is there a list of such operators? Would be helpful to know. By the way why did you not use data attributes
@sinhavartika There is a list here api.jquery.com/category/selectors There is no reason to use data-attributes when you can easy create what the op wanted without
There is nothing wrong with data attributes, but I don't see a reason to use them if they are not needed
|
7

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>

1 Comment

this should be the approved answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.