Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
  }
});
like image 790
user1554264 Avatar asked Oct 20 '22 00:10

user1554264


2 Answers

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
});
like image 56
Tushar Avatar answered Nov 02 '22 09:11

Tushar


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 
  }
});
like image 20
Rajaprabhu Aravindasamy Avatar answered Nov 02 '22 08:11

Rajaprabhu Aravindasamy