jquerythisjquery-backstretch

Why does not "$(this)" work width .data on jquery-backstretch?


So I am trying to get $(this) to work.

This does not work:

$(".tournament-thumb").backstretch($(this).data("url"));

But this does:

$(".tournament-thumb").backstretch($(".tournament-thumb").data("url"));

I need to take the url from the data. Here is the HTML:

<div class="tournament-thumb" data-url="{{asset('images/tournament/' . $tournament->image)}}">

Am I missing some vital part with $(this) and .data ?


Solution

  • using this in an parameter statement,does not change its context. it still refers to the same object as it were anywhere else in the surrounding scope

    function x(){
        //this in here and the function parameter call refers to the same object
        console.log(this)
        $(".tournament-thumb").backstretch($(this).data("url"));
    }
    

    in jQuery, if you pass a callback to a function, inside those functions this will most probably refer to the dom element currently being used.

    If it were something like

    $(".tournament-thumb").backstretch(function(){
        //do something
        //here this might refer to the tournament-thumb element
    });