1

I want to get access to DOM-Elements which are added with jquery from an external HTML-File.

Here's my first part of the code where I add the HTML:

$.get("resources/game/game_menu.html").success(function(data) {
    $("#gameView2").html(data);
});

the "game_menu.html" looks just like this (atm for testing)

<div id="gameMenu" class="gameMenu">
    <button id="startGame" type="button">Click Me!</button>
</div>

Now I'm trying to get access to the elements with jquery which looks like this:

$("#startGame").click(startGame());
$("#gameMenu").someFunction(someContext);

But both just don't work. How is possible to get access to ALL of the DOM-Elements. Can anyone help me?

Thx, myr0

myr0
  • 47
  • 8
  • Where do you put the last two commands? Can you show the whole code please? –  May 20 '16 at 16:20

2 Answers2

1

You need to use $(document).on("click", "#startgame", startGame()); for dynamically generated content.

See Click event doesn't work on dynamically generated elements for the reason why you have to do this.

Community
  • 1
  • 1
Matt Solarz
  • 146
  • 1
  • 8
0

Define the event inside

$.get("resources/game/game_menu.html").success(function(data) {
    $("#gameView2").html(data);
    $("#startGame").click(startGame());
});

Those elements not exist in DOM.

Omar Vega
  • 5
  • 3