3

i seem to repeat alot of functions when coding something simple, is there a better way of doing this?

  $('#bt1').click(function() {
      $('#txt1').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

  $('#bt2').click(function() {
      $('#txt2').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

  $('#bt3').click(function() {
      $('#txt3').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

  $('#bt4').click(function() {
      $('#txt4').show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 

so that i'm not repeating code?

Ma9ic
  • 1,107
  • 4
  • 16
  • 30

4 Answers4

6

Give your buttons a class, such as btn, and then you can do something like:-

$('.btn').click(function() {
  $('#' + this.id.replace('bt', 'txt')).show();
  $(this).css("background-image", "url(site_images/08/btn_over.png)"); 
});
billyonecan
  • 20,090
  • 8
  • 42
  • 64
  • if I cought it right, this doesn't cover different texts which user want to display ... #txt1 .. #txt[n] – Lukas Greso May 13 '13 at 09:34
  • 1
    @LukasGreso It does. It takes the ID of the button that was clicked on (e.g. `bt1`) then replaces the `bt` part with `txt` to get the ID of the associated text to show; it's the first line of the event handler function. – Anthony Grist May 13 '13 at 09:36
  • YES YES, I see ... sorry :) – Lukas Greso May 13 '13 at 09:36
3

You can try to use attribute Starts With Selector:

$("[id^='bt']").click(function() {
      var number = $(this).prop('id').slice(-1);
      $('#txt' + number).show();
      $(this).css("background-image", "url(site_images/08/btn_over.png)");  
}); 
Eli
  • 14,779
  • 5
  • 59
  • 77
1

How about this,

$('#bt1,#bt2,#bt3,#bt4').click(function () {
    var number = this.id.replace( /^\D+/g, '');
    $('#txt'+number).show();
    $(this).css("background-image", "url(site_images/08/btn_over.png)");
});

note: better if you can add a class for all the items need to click. and then selecter will be changed to class name. rest of the code is same

Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
0

Use Multiple Selector

$('#bt1, #bt2, #bt3, #bt4').click(function () {
    var number = this.id.replace( /^\D+/g, '');
    $('#txt'+number).show();
    $(this).css("background-image", "url(site_images/08/btn_over.png)");
});

You can also .add() selectors: How to combine two jQuery results

Community
  • 1
  • 1
Danubian Sailor
  • 1
  • 38
  • 145
  • 223