2

I had this script working before when it was just an inline script on a WordPress page. But now I load it from function.php.

This works fine for my other JavaScript scripts, but .click or .on won't work on this script...

$( "td.event-test" ).on("click",
  function() {
    $("p").empty();
    $(".event-title").empty();
    $(".event-title2").empty();
    $("<h1>EVENT #01</h1>").appendTo(".event-title");
    $("<p>Here is information for event!</p>").appendTo(".event-info");
    $("<p>more info for event</p>").appendTo(".more-event-info");
    $("<p><a>LINK TO EVENT SITE</p></a>").appendTo(".event-link");
    $("a").attr("href", "events");
  }
);

It won't work, and the .click version won't work either:

$( "td.event-test" ).click(
  function() {
    $("p").empty();
    $(".event-title").empty();
    $(".event-title2").empty();
    $("<h1>EVENT #01</h1>").appendTo(".event-title");
    $("<p>Here is information for event!</p>").appendTo(".event-info");
    $("<p>more info for event</p>").appendTo(".more-event-info");
    $("<p><a>LINK TO EVENT SITE</p></a>").appendTo(".event-link");
    $("a").attr("href", "events");
  }
);

It loads the script as I can see console.log printing "test" string from the first line of the JavaScript script.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    Did you put that code inside a proper DOM ready handler with no-conflict, as required by Wordpress, and did you include it with `wp_enqueue_script` – adeneo Jul 20 '17 at 13:32
  • This lines are the same thing.... under the hood, `click(` changes to on("click" – epascarello Jul 20 '17 at 13:34

1 Answers1

0

You have to use event delegation:

$(document).on("click","td.event-test",function() {
    $("p").empty();
    $(".event-title").empty();
    $(".event-title2").empty();
    $("<h1>EVENT #01</h1>").appendTo(".event-title");
    $("<p>Here is information for the event!</p>").appendTo(".event-info");
    $("<p>More info for the event</p>").appendTo(".more-event-info");
    $("<p><a>LINK TO THE EVENT SITE</p></a>").appendTo(".event-link");
    $("a").attr("href", "events");
});

Note: I have added this answer, because I saw on() in OP's code, so I thought that the OP was thinking on() will directly work for dynamically generated elements also, which is not right. That's why I added this solution so that it will work for both scenarios.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98