user1554264
user1554264

Reputation: 1224

Jquery - prevent default action of <a> on first click, allow default action on second click

How would I prevent the default action of an <a> on the first click (in order so that a tooltip is shown), then on the second click have the user directed to the value of the href attribute set on the element?

HTML

<a id="second" href="https://www.test.com/"  title="" class="customtooltip c_tool2"   data-original-title="data del toolltip numero 2">tooltip</a> 

Jquery

var t = $('.c_tool2'), b = $('a[href^="http');

b.click(function(e){
  if(t.length > 0){
    e.preventDefault();
    t.tooltip('show');
  } else {
    // on second click direct user to value of href 
  }
});

Upvotes: 5

Views: 1141

Answers (2)

Tushar
Tushar

Reputation: 87203

Assuming there will be multiple elements, using a common counter will not work. You can use counter on individual element using data-* attribute

Also, the selector to select the anchors is incorrect.

var t = $('.c_tool2'),
    b = $('a[href^="http"]'); // <-- Added "] to make it correct

b.click(function (e) {
    // Get the counter for clicked element
    var clickCount = parseInt($(this).data('count'), 10) || 0;

    // If counter is zero i.e. for the first click
    if (!clickCount) {
        // Update the value of the counter
        $(this).data('count', ++clickCount);
        t.tooltip('show');

        // Prevent the default action of the page redirection
        e.preventDefault();
    }

    // Else, follow the default action
});

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to make use of .data() instead of polluting the global scope with counters,

b.click(function(e) {
  if(!$(this).data("flag")) {
    e.preventDefault();
    $(this).data("flag",true);
    t.tooltip('show');
  } else {
    // on second click direct user to value of href 
  }
});

Upvotes: 1

Related Questions