Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating functions

Tags:

jquery

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?

like image 809
Ma9ic Avatar asked Feb 13 '26 06:02

Ma9ic


2 Answers

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)"); 
});
like image 120
billyonecan Avatar answered Feb 15 '26 20:02

billyonecan


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)");  
}); 
like image 32
Eli Avatar answered Feb 15 '26 19:02

Eli