Minify js code using jQuery

How to attach same function with multiple HTML elements by a single line js code using jQuery

Recently I was working on a online shopping cart and auctioning site which required a lot of

Javascript code. Each page in the site had a number of “Buy” or “Bid” links associated with different HTML Ids. For instance, if a particular page has 5 Bid links, then the Ids are named as “bid1″,”bid2”, “bid3” etc.. A major functionality of the application required that, on click, we programatically check if the user is logged in or not and attach function accordingly. In other words the application would attach a particular function if the user is logged in but if s/he is not logged in another function would be called.

I wrote a huge javascript code to do this for every element using normal js DOM but it was very painful for me to write same code multiple times and then debug it.

The HTML code looked like following:








The Javascript Function:
 


document.getElementById("bid1").onclick = document.getElementById("post_bid").modal();
document.getElementById("bid2").onclick = document.getElementById("post_bid").modal();
document.getElementById("bid3").onclick = document.getElementById("post_bid").modal();
document.getElementById("bid4").onclick = document.getElementById("post_bid").modal();



document.getElementById("bid1").onclick = document.getElementById("login").modal();
document.getElementById("bid2").onclick = document.getElementById("login").modal();
document.getElementById("bid3").onclick = document.getElementById("login").modal();
document.getElementById("bid4").onclick = document.getElementById("login").modal();



$(document).ready(function () {
 $('.basic3').click(function (e) {
  e.preventDefault();
  $('#post_bid').modal();
 });
});



$(document).ready(function () {
 $('.basic3').click(function (e) {
  e.preventDefault();
  $('#login').modal();
 });
 
});


?>
150 150 Burnignorance | Where Minds Meet And Sparks Fly!