Confirming a Link Click with jQuery

28 July 2011 on JavaScript. 1 minute

Here's a function I wrote while working on a project that pops up a box confirming whether or not the user is sure the want to go to a link they clicked, like this.

It may be simple, but I haven't really used javascript's confirm() function much in the past and everything I found only directed the user to a link predefined in the function. I wanted a function that would confirm any link I wanted it to without knowing the link destination in advance, in other words I wanted to confirm dynamic links.

The Code

This jQuery function will pop up a confirmation box on any link with the class confirm and send the user to the destination of that link if they click 'OK'.

$(function() {
  $('a.confirm').click(function(event) {
    event.preventDefault()
    var url = $(this).attr('href');
    var confirm_box = confirm('Are you sure you want to click this link?');
    if (confirm_box) {
       window.location = url;
       //uncomment below and remove above if you want the link to open in a new window
       //window.open(url,'_blank');
    }
  });
});

Link Code

<a href="http://www.grimmdude.com/contact/" class="confirm">Link Example</a>

Previous

Select All Text Box Wordpress Plugin

Here's another simple WordPress plugin I came up with. I was trying to figure out an easy way to create a text box for some song lyrics which, once clicked, selected everything inside so anyone could easily copy and past the contents. Well, once I figured out how to make it I figured I would make it easier for others who want to do the same thing. Hence, Simple Select All Text box was born.

Next

menuFlip - jQuery Plugin for Flipping Navigation

Here's another simple WordPress plugin I came up with. I was trying to figure out an easy way to create a text box for some song lyrics which, once clicked, selected everything inside so anyone could easily copy and past the contents. Well, once I figured out how to make it I figured I would make it easier for others who want to do the same thing. Hence, Simple Select All Text box was born.