JQuery - prevent the default action <a> on the first click, allow the default action on the second click
How can I prevent the default action on the <a>
first click (so that the tooltip is shown), and then in the second click the user accesses the attribute value href
set to 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
}
});
+4
3 answers
Assuming there will be several elements, using a common counter will not work. You can use the counter for an individual element using the attributedata-*
In addition, the selector for selecting 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
});
+2
Oh, you have nothing to count. Just use jQuery.one
to attach the tooltip handler:
The .one () method is identical to .on (), except that the unbound handler is after the first call.
$(function() {
$(".customtooltip").one("click", function(e) {
e.preventDefault();
$(this).text("Click again to open");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a class="customtooltip" href="https://www.example.com/#1">Link 1</a>
<a class="customtooltip" href="https://www.example.com/#2">Link 2</a>
<a class="customtooltip" href="https://www.example.com/#3">Link 3</a>
0