Question

I am trying to jQuery to calculate the amount of times a ID has been clicked. for instance if #kwick_1 is clicked once, I want it to load the video 'else' do nothing.

And I am looking at applying this throughout the function so the same goes for 2, 3, 4 etc.

How would I achieve this?

var timesClicked = 0;
  $('#kwick_1, #kwick_2, #kwick_3, #kwick_4, #kwick_5, #kwick_6, #kwick_7').bind('click', function(event){
   var video = $(this).find('a').attr('href'); /* bunny.mp4 */

   var clickedID = $(this).attr('id'); /* kwick_1 */
   var vid = 'vid';
   timesClicked++;

   $(this).removeAttr('id').removeAttr('class').attr('id',clickedID + vid).attr('class',clickedID + vid);
   if(timesClicked == 1) {

    $.get("video.php", { video: video, poster: 'bunny.jpg', }, function(data){
     $('.'+clickedID+vid).html(data);
    }); 

   } else {
    /* Do nothing for now */
   }
   return false;
  });
Was it helpful?

Solution

You can use .one() to do this a bit easier, like this:

$('#kwick_1, #kwick_2, #kwick_3, #kwick_4, #kwick_5, #kwick_6, #kwick_7').one('click', function(event){
  var video = $(this).find('a').attr('href'), clicked = this.id + 'vid';

  $(this).attr({ id: clicked, 'class': clicked });
  $.get("video.php", { video: video, poster: 'bunny.jpg', }, function(data){
    $('.'+clicked).html(data);
  }); 
}).click(function() { return false; });

The rest is just optimization and cutting down on repeated code, but the idea is to bind the part you only want to happen once using .one(), then that handler will remove itself after the first execution. Then we're binding the return false using .click() since that one should always happen. Make sure this is bound after like the example above, since event handlers are run in the order they were bound.

Also you could replace your #kwick_1, #kwick_2.... selector with .kwick if you could give them all a class, this above would still work and be much easier to maintain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top