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

1
  • Where do you put the last two commands? Can you show the whole code please? Commented May 20, 2016 at 16:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

$(document).on("click", "#startgame", startGame);
$(document).on("click","#startGame", function(){ startGame() }); this fixed it! thx!
Alex is right, you can just pass in startGame instead of function() { startGame() }, but the way you've done it should be fine as well.
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.

1 Comment

startGame shouldn't have () I think, as it's a callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.