0

I'm missing some javascript basics. I'm using the code bellow very often and I would like to simplify it:

 $("#someLink").on('click', function (e) {
      e.preventDefault();
      var link = $(this).attr('href');
      $.confirm({
           confirm: function () {
                title: 'I would like a variable here'
                window.location.href = link;
           }
      });
 })

To something like:

//somehow define myConfirm function here
//so the code below can be used in a similar simple way and it would do the same as the first code snippet in the post.
$("#someLink").myConfirm(title);

Probably this would work but is it the best way?:

function myConfirm($object,title){
     $object.on('click', function (e) {
          e.preventDefault();
          var link = $(this).attr('href');
          $.confirm({
               confirm: function () {
                    title: title
                    window.location.href = link;
               }
          });
     })
}    
myConfirm($linkObject, title);

I'm not sure how this thing $.confirm is called. Is it a plugin? Can it be somehow made for links too? I would study this more myself but I think this question comprehends multiple javascript topics and I don't know where to start from.

1
  • 1
    Yes, $.confirm is a jQuery plugin (as a static method), but I don't think there's any reason to make myConfirm a jQuery method. It's completely fine in a standalone function. Commented Nov 5, 2015 at 23:24

1 Answer 1

1

Yes, jQuery plugin.

$.fn.myConfirm = function(title) {
  this.on('click', function (e) {
    // ...
  });
};

$('#someLink').myConfirm(title)

Note that this does not work with plain JS, as it is a jQuery feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.