trying to extract a string from a js this keyword

82 views Asked by At

I'm trying to execute javascript after a link is clicked before loading the link, using this code:

$('body').on("click", 'a', function (evt) {
            evt.preventDefault();
            console.log(this);
            $('.content').addClass('hide');
            if (this.search("AV") > 0) {
                $('#AVheader').addClass('fullwidth');
            }
            setTimeout(function () {
                window.open(this, "_self");
            }, 500);
        });

My errors are:

this.search Isn't a function and

window.open(this, "_self"); doesn't work

Wanted to put the question out there since I couldn't find a simple explanation and I'd probably spend half a day trying to figure it out..

2

There are 2 answers

1
dreyescat On BEST ANSWER

When you are in the event handler this points to the clicked link. There is no search method for an element. Probably you are trying to search for a string somewhere in the link, maybe the content.

    $('body').on("click", 'a', function (evt) {
        evt.preventDefault();
        console.log(this);
        $('.content').addClass('hide');
        if (this.innerHTML.search("AV") > 0) {
            $('#AVheader').addClass('fullwidth');
        }
        setTimeout(function () {
            window.open(this.href, "_self");
        }.bind(this), 500);
    });
1
Patrick Evans On

this inside the timeout function will not reference your anchor element, it will instead reference the global window object. You will need to save a reference to the element and then use that reference inside the timeout callback

$('body').on("click", 'a', function (evt) {
  evt.preventDefault();
  //save the "this" reference
  var that = this;
  $('.content').addClass('hide');
  if (this.search.search("AV") > 0) {
    $('#AVheader').addClass('fullwidth');
  }
  setTimeout(function () {
    window.open(that.search, "_self");
  }, 500);
});

Also .search property on the anchor element is not a function it is a string, you would have to do this.search.search("AV") or this.href.search("AV") depending on what you are actually trying to search on