Joel
Joel

Reputation: 895

How to do something on pageload in jQuery AND onclick after?

I have some javascript:

// when page LOADS:
// update PassMark score
$("#passmark").attr("onclick", "window.open('https://www.google.ca/search?num=20&q=site%3Avideocardbenchmark.net+" + encodeURIComponent( $("input[name='vc_gpu_engine']").val() ).replace(/%20/g, "+") + "', 'url', 'status,scrollbars=yes,height=900,width=1050').focus();");

// if any field is changed AFTER the page loads, then run these
$("body").click(function() {

  // update PassMark score
  $("#passmark").attr("onclick", "window.open('https://www.google.ca/search?num=20&q=site%3Avideocardbenchmark.net+" + encodeURIComponent(     $("input[name='vc_gpu_engine']").val() ).replace(/%20/g, "+") + "', 'url', 'status,scrollbars=yes,height=900,width=1050').focus();");

});

Now like any programmer, I like to keep code to a minimum.

Is there a way to avoid duplicating the same command?

Can I run the same line of code both when page loads and when the user clicks anywhere?

Thanks

Upvotes: 0

Views: 51

Answers (2)

void
void

Reputation: 36703

var func = function () {
    $("#passmark").attr("onclick", "window.open('https://www.google.ca/search?num=20&q=site%3Avideocardbenchmark.net+" + encodeURIComponent($("input[name='vc_gpu_engine']").val()).replace(/%20/g, "+") + "', 'url', 'status,scrollbars=yes,height=900,width=1050').focus();");
}


$(document).ready(function () {
    func();
    $("body").click(function () {
        func();
    });
});

This way you can use the func() afterwards as well.

EDIT Even Shorter

var func = function () {
    $("#passmark").attr("onclick", "window.open('https://www.google.ca/search?num=20&q=site%3Avideocardbenchmark.net+" + encodeURIComponent($("input[name='vc_gpu_engine']").val()).replace(/%20/g, "+") + "', 'url', 'status,scrollbars=yes,height=900,width=1050').focus();");
}

$(function(){
  func();
  $("body").click(func);
});

Upvotes: 3

dfsq
dfsq

Reputation: 193261

Bind event handler and trigger it immediately:

$("body").click(function() {

    // update PassMark score
    $("#passmark").attr("onclick", "window.open('https://www.google.ca/search?num=20&q=site%3Avideocardbenchmark.net+" + encodeURIComponent( $("input[name='vc_gpu_engine']").val() ).replace(/%20/g, "+") + "', 'url', 'status,scrollbars=yes,height=900,width=1050').focus();");

}).click();

Upvotes: 0

Related Questions