Question

For some practice this week, I tried creating the front end of a blog page. I added a few "fake" Like buttons (they don't attach to facebook, just raise a counter that's placed next to them.)

Everything works, though I think there's a more direct and re-usable way to write the jQuery/JavaScript code I used to build those counters.

Here's the JavaScript code:

<script>
var whichButton = "";
var counter = 0;                        // Adds counters next to each 
var counter2 = 0;                       // "Like" button, and raises
$("button").on("click", function(){     // their values separately.
  whichButton = this.id;                   
  if (whichButton === "button1") {        
    counter++; 
    $("#span1").html(counter);
  } else {
    counter2++
    $("#span2").html(counter2);
  }
});
</script>

...and here's the html it affects:

<button id="button1">Like</button>
<span id="span1"></span>
<button id="button2">Like</button>
<span id="span2"></span> 

Is there a less hands-on way to write this code? Something that would allow me to add new buttons alongside new spans, both with complementary ids, and, without updating my JavaScript code, have my site allow each button to function automatically?

I'm trying to write this in the most efficient way I can.

Thanks!

Was it helpful?

Solution

To make this a more reusable component, take advantage of classes instead of unique IDs.

$(".like_button button").on("click", function() {
  var $count = $(this).parent().find('.count');
  $count.html($count.html() * 1 + 1);
});

In your markup, create as many like_button instances as you want, and use the HTML to set the default value of 0.

<div class="like_button">
  <button>Like</button>
  <span class="count">0</span>
</div>

Note: $(this).parent().find('.count'); is a very literal traversing example. You could use $(this).next(); instead to find the button's next sibling, which would remove the need for the "count" class. Check out the jQuery Docs on Traversal for many other wonderful methods.

Here's a fiddle showing that in action: http://jsfiddle.net/bw5LU/

OTHER TIPS

Sure, mark all the like buttons with a class or other attribute so we can select like:

$(".like-button").on("click", function(e){
    var $counter = $(this).find(".count");
    var count = $counter.text() | 0; //corose current count to an int
    $counter.text(count + 1);//set new count
});

Now to create new like buttons add the following snippet anywhere in your html document:

<div class="like-button">
    <button>Like</button>
    <span class="count"></span>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top