Search code examples
jqueryattributeshref

Is there a more optimal way to write this jQuery code that adds a _blank attribute to targeted links (opens them in a new tab)?


Here's the code I'm working with. Is this the optimal way to write it? Can I do better?

// Open External URLs and PDFs in New Tab
$(document).ready(function () {
    $(document).on("click", 'a[href^="http"]', function () {
        $(this).attr("target", "_blank");
    });
    $(document).on("click", 'a[href$=".pdf"]', function () {
        $(this).attr("target", "_blank");
    });
});

Solution

  • You can combine the selectors into just one event listener

    $(document).on("click", 'a[href^="http"], a[href$=".pdf"]', function () {
        $(this).attr("target", "_blank");
    });