Karolina Ticha Karolina Ticha - 3 months ago 4
Javascript Question

$(this) doesnt work with javascript created elements?

I can't find out why my script can't work. Here is simple table:

<td>Paul Stevenson</td>
<td>28. 09. 1978</td>

My script adds link to th elements.

var toolbar = $("<div />");
var link = $("<a />").attr({"target" : "_blank"});
toolbar.append( gmaps );

When user moves cursor to th element, it shows the toolbar.

$('th').on("mouseenter mouseleave", function(e) {
if (e.type === 'mouseenter') { $(this).append( toolbar ); }
else { $(this).find( $("div") ).remove() }

Why my variable

var thisNext = $(this).parent().next().text();

Does not get the td text and do not add it to link?

You can see codepen as well


When you do $(this) inside the function

$('th').on("mouseenter mouseleave", function(e) {

then the $(this) is pointing to the th element but when you are accessing the $(this) to get the text

var thisNext = $(this).parent().next().text();

it is outside the function and here $(this) points to the window object.

if you need to select the text using the proper selector here. check more here http://www.w3schools.com/jquery/jquery_selectors.asp

this is the updated code for what you are trying to achieve.

$('th').on("mouseenter mouseleave", function(e) {

  if (e.type === 'mouseenter') { 

    var toolbar = $("<div />").css({
      "padding": "5px",
      "background" : "#F8F8F8",
      "position" : "absolute",
      "borderRadius" : "5px 0 5px 5px",
      "left" : "-30px",
      "top" : "0",
      "zIndex" : "99"

    var link = $("<a />").css({
        "display" : "block",
        "height" : "20px",
        "width" : "20px",
        "marginBottom" : "5px",
        "background-size" : "100%",
        "position" : "relative"}).attr({
          "target" : "_blank"
    var thisNext = $($(this).parent().children('td')[0]).text();
    var gmaps = link.clone().css({"background" : "red"}).attr({
        href: 'https://www.google.cz/search?q=' + thisNext });
    toolbar.append( gmaps );
    $(this).append( toolbar ); }

codepen: http://codepen.io/deep2701/pen/YWVkkA?editors=0010#anon-signup

Hope this will help you.