views:

55

answers:

3

I have a page with a linked image, where the link takes a bit of time to load. Therefore, users tend to click multiple times on it. This occasionally causes errors to crop up in the code. How do I prevent users from clicking on the link more than once?

In an attempt to remedy this, I changed the link to an onClick event and then in the function I used the code:

$('#myImageId').unbind('click');
window.location.href = "myLink";

However, that doesn't seem to be helping. Also, I'd prefer to keep it a simple linked image instead of using javascript.

A: 

A hacky CSS solution that might/might not work: create another image element, without the link and make it a sibling to the link, like this:

<div>
  <a href="http://www.long-loading.com" id="link"><img src="my_img.png" id="img_link" alt="GO" /></a>
  <img src="my_img.png" id="img_nolink" alt="GO" />
</div>

Now apply this CSS:

#img_nolink { display: none; position: relative; top: -200px; /* Height of the image */ }

#link:active + #img_nolink { display: block; }

This should show the non-link image when the link is clicked (theoretically).

dark_charlie
+1  A: 
<img src="..." id="myImageId">


$('#myImageId').bind('click', function() {
    $(this).unbind('click');   
    /* do long time task....
});

if your image is wrapped by a link the code will be

<a href="#"><img src="..." id="myImageId"></a>


$('#myImageId').parent().bind('click', function(evt) {
    $(this).unbind('click');   
    /* do long time task....

    evt.preventDefault();
});
Fabrizio Calderan
+3  A: 

Once solution is to add a class to the element that is used as a flag to determine of the code should run.

Here's an example: http://jsfiddle.net/qLhr8/

$('#myImageId').click(function() {
   var $th = $(this);
   if( !$th.hasClass( "pending" ) ) {
           // Add the "pending" class, so subsequent clicks will not
           //   run the code inside this if()
       $th.addClass( "pending" );
       window.location.href = "myLink";
       // you could do a setTimeout to remove the class
       //   if the new page never loads
   }
});

With the added class, you can also change the look of the image (lower its opacity perhaps) to indicate that it shouldn't be clicked again.

.pending {
    opacity: .4;
    filter:alpha(opacity:40);
    cursor: wait;
}
patrick dw
Simple and elegant with a good user experience by letting them know that something's happening. I like it.
Babak Naffas