simPod
simPod

Reputation: 13466

Javascript basics – is there a way to reuse the code without using standard function?

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.

Upvotes: 0

Views: 48

Answers (1)

Amadan
Amadan

Reputation: 198408

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.

Upvotes: 1

Related Questions