Search code examples
javascriptjqueryundefinedhrefattr

jquery $(this).attr('href') returns undefined


I've got a very simple code

HTML

<a class="qqPopupCTA" href="http://example.com">Button</a>

JS

$qqPopupCTA = $('.qqPopupCTA');

function showForm(e){

    e.preventDefault();

    var targetPageUrl = $(this).attr('href');

    // do stuff
}

$qqPopupCTA.on('click', function(e){showForm(e);});

However I keep getting undefined href. Console.log($(this)) returns "window" and console.dir($(this)) returns "e.fn.init[1]"

Any idea what am I doing wrong? The code is super simple so I must be missing something obvious.

I think I've tried everything.


Solution

  • When you call showForm(e), the context(this) is not the anchor object inside showForm it is the window object.

    So you can just pass the function reference as the click handler

    $qqPopupCTA.on('click', showForm);
    

    $qqPopupCTA = $('.qqPopupCTA');
    
    function showForm(e) {
      e.preventDefault();
      var targetPageUrl = $(this).attr('href');
      alert(targetPageUrl)
    
      // do stuff
    }
    
    $qqPopupCTA.on('click', showForm);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <a class="qqPopupCTA" href="http://example.com">Button</a>

    or pass a custom context to the showForm function using .call()

    $qqPopupCTA.on('click', function (e) {
        showForm.call(this, e);
    });
    

    $qqPopupCTA = $('.qqPopupCTA');
    
    function showForm(e) {
      e.preventDefault();
      var targetPageUrl = $(this).attr('href');
      alert(targetPageUrl)
    
      // do stuff
    }
    
    $qqPopupCTA.on('click', function(e) {
      showForm.call(this, e)
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <a class="qqPopupCTA" href="http://example.com">Button</a>