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?
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)");
});
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)");
});
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